問題描述
我正在編寫一個代碼段,它遍歷 n 位數字的每個排列.例如,如果 n = 3,我想遍歷以下每個元素:
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
使用嵌套的 for 循環很容易編寫代碼:
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)
但我想將其概括為 n 位數字.例如,如果 n = 10,我現在需要 10 個嵌套的 for 循環.
But I want to generalize this for n digits. If for example n = 10, I now need 10 nested for loops.
我已經考慮過這個問題,并意識到可以使用遞歸解決問題(深度優先搜索一棵樹,每個節點有 10 個子節點,從 0 到 10,并在深度 n 處停止).但我的目標是高性能,所以我不想因為開銷而使用遞歸.我還有什么其他選擇?
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?
推薦答案
如果你想在不使用遞歸的情況下用單個循環模擬嵌套循環,你可以通過為每個循環變量維護一組狀態(或槽)來實現,這可以通過數組輕松完成.循環然后變成一個簡單的問題,即向該數組加 1",根據需要執行進位操作.如果您的嵌套深度是 n,并且每個循環的最大邊界是 b,那么它的運行時間是 O(b^n),因為進位操作只會最多花費你 O(b^n)(我會在這里跳過代數).
If you want to simulate nested loops with a single one without using recursion, you can do so by maintaining a set of states (or slots) for each looping variable, which can be easily done with an array. Looping then turns into a simple matter of "adding 1" to that array, performing the carry operations as needed. If your nesting depth is n, and your maximum boundary for each loop is b, then the runtime of this is O(b^n), because the carry operations will only cost you at most O(b^n) (I'll skip the algebra here).
這是工作的 C++ 代碼(更新以整合 Drew 的評論):
Here is the working C++ code (updated to integrate Drew's comment):
void IterativeNestedLoop(int depth, int max)
{
// Initialize the slots to hold the current iteration value for each depth
int* slots = (int*)alloca(sizeof(int) * depth);
for (int i = 0; i < depth; i++)
{
slots[i] = 0;
}
int index = 0;
while (true)
{
// TODO: Your inner loop code goes here. You can inspect the values in slots
// Increment
slots[0]++;
// Carry
while (slots[index] == max)
{
// Overflow, we're done
if (index == depth - 1)
{
return;
}
slots[index++] = 0;
slots[index]++;
}
index = 0;
}
}
這篇關于C++:嵌套for循環的動態數量(無遞歸)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!