Answering your own question if you figure out the problem yourself is not only allowed but encouraged. In fact, the only two questions I've ever asked on SO I've answered myself. You might notice there's a checkbox when composing your question that allows you to immediately answer your own question, with a link to this SO blog post. So, given that the site explicitly added a feature allowing you to do it, yes. You should answer your own question.
Your reasoning is completely correct -- the whole reason for doing it is so that you can help others in the future and avoid situations like the one in this XKCD where you find an ancient comment saying something like "nvm solved it lol" and you leave unsatisfied. And, even if you're feeling selfish, you should still do it since you're liable to gain some rep if others find your self-answer useful (on one of my self-answered Q's, the answer has more total score than the question, oddly enough).