打印一个数组的全排列,要求非递归。
模拟递归当然会想到用栈模拟,最主要的是考虑初始的压入栈中的值,这里首先想到递归调用是用一个for循环遍历0到n-1的索引,看哪个可以用(比如k)就递归调用函数,然后返回的时候在k+1继续循环查找下去。这里的关键是如何能模拟循环的一个过程,于是我考虑到用出栈的值的下一个值来继续for循环的下一个值,于是初始从0开始,我们就可以先压入-1,然后再把它弹出栈,取下一个值作为for循环的初始值。然后当栈大小>n时打印。
1 #include <iostream>
2 #include <vector>
3 #include <stack>
4 using namespace std;
5
6 void permutation(int a[], int n)
7 {
8 vector<int> b(n);
9 vector<bool> canUse(n);
10
11 for(int i = 0; i < n; i++)
12 canUse[i] = true;
13
14 stack<int> s;
15
16 s.push(-1);
17
18 while(!s.empty())
19 {
20 if (s.size() > n)
21 {
22 for(int i = 0; i < n; i++)
23 cout << b[i] << ' ';
24 cout << endl;
25 s.pop();
26 continue;
27 }
28
29 if (s.top() >= 0)
30 canUse[s.top()] = true;
31
32 int start = s.top() + 1;
33 s.pop();
34 for(int i = start; i < n; i++)
35 if (canUse[i])
36 {
37 canUse[i] = false;
38 b[s.size()] = a[i];
39 s.push(i);
40 s.push(-1);
41 break;
42 }
43 }
44 }
45
46 int main()
47 {
48 int a[] = {1, 2, 3};
49
50 int aSize = sizeof(a) / sizeof(int);
51
52 permutation(a, aSize);
53 }
来源:https://www.cnblogs.com/chkkch/archive/2012/10/31/2748910.html