Solution for problem 24.
Helper function to generate permutations.