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:
https://www.adamk.org/leetcode-31-next-permutation/

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:
https://gist.github.com/adamkorg/1d306abeb41eede8ff0dab43e1569d25
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.