Suppose you need to discover all possible permutations of 'n' distinct characters, say 'a', 'b', 'c'. Can you suggest an algorithm I can use to get this done? Generally speaking, how would you go about it?
+1
A:
Let 'Perms' be the collection of permutations found, and 'Used' be a list of the characters currently selected.
To find permutations of n chars from a set S:
- If n = 0, then Used is a permutation. Add it to Perms and return.
- For each char C in S:
- Remove C from S and append (or push) it to U.
- Find permutations of n-1 chars from S.
- Remove the end of (or pop) U and add C to S.
When you've returned from finding permutations of n chars, Perms contains all the possible permutations.
Note, this is all done using sets and lists. There are lighter-weight alternatives, but these structures make the steps more straightforward, so i used them.
cHao
2010-07-20 03:44:14