I'm writing a code segment that iterates through every permutation of n digits. So for example, if n = 3, I would want to iterate through each of the following elements:
0, 0, 0
...
0, 1, 0
...
1, 0, 0
...
2, 3, 4
...
9, 9, 9
This is very easy to code using nested for loops:
for(digit1 0 to 9)
for(digit2 0 to 9)
for(digit3 0 to 9)
But I want to generalize this for n digits. If for example n = 10, I now need 10 nested for loops.
I've thought about this and realized that the problem can be solved using recursion (depth first search through a tree, with each node having 10 children, 0 to 10, and stopping at depth n). But I'm aiming for high performance so I don't want to use recursion due to the overhead. What other alternatives do I have?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…