Leetcode 46: Permutations

The obvious way to solve this is to repeatedly call next_permutation() from the standard library. Another way to solve it is to implement what next_permutation() does and I have done that in a previous solution:

Here is my recursive solution with backtracking. The nums parameter is the pool of numbers to choose from and the sel parameter is the current selection. We start with nums full and as we recurse we will get to a state where nums is empty and sel is full and at that point we add sel to our result set.

Here is the source code for the next_permutation based solution:
And here is the code for the recursive solution:

A more efficient solution is https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ although this does not generate outputs in lexicographical order.

This entry was posted in programming and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *