I need to efficiently calculate the next permutation of length k
from n
choices. Wikipedia lists a great
algorithm
for computing the next permutation of length n
from n
choices.
The best thing I can come up with is using that algorithm (or the Steinhaus–Johnson–Trotter algorithm), and then just only considering the first k
items of the list, and iterating again whenever the changes are all above that position.
Constraints:
- The algorithm must calculate the next permutation given nothing more than the current permutation. If it needs to generate a list of all permutations, it will take up too much memory.
- It must be able to compute a permutation of only length
k
ofn
(this is where the other algorithm fails
Non-constraints:
- Don't care if it's in-place or not
- I don't care if it's in lexographical order, or any order for that matter
- I don't care too much how efficiently it computes the next permutation, within reason of course, it can't give me the next permutation by making a list of all possible ones each time.