33,007
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
2 #include <assert.h>
3 #define swap(A, a, b, tmp)\
4 {\
5 (tmp) = A[(a)];\
6 A[(a)] = A[(b)];\
7 A[(b)] = (tmp);\
8 }
9
10
11 void print_r(const int A[], int len);
12 void perm(int A[], int start, int end, int len);
13
14 int main()
15 {
16 int A[4] = {1, 2, 3, 4};
17
18 perm(A, 0, 3, 4);
19
20 return 0;
21 }
22
23 void print_r(const int A[], int len)
24 {
25 assert(NULL != A);
26 int i;
27 for (i = 0; i < len; i++)
28 printf("%d ", A[i]);
29 printf("\n");
30 }
31
32 void perm(int A[], int start, int end, int len)
33 {
34 assert(NULL != A);
35 int i, tmp = 0;
36
37 if (start == end) {
38 print_r(A, len);
39 } else {
40 for (i = start; i <= end; i++) {
41 swap(A, i, start, tmp);
42 perm(A, start+1, end, len);
43 swap(A, i, start, tmp);
44 }
45 }
46 }
stack<char> a; //源栈
stack<char> stac; //中间栈
vector<char> outL; //目的容器,保存最后的出栈的元素
void finn()
{
if(a.empty() && stac.empty()){
for(unsigned int i=0; i<outL.size(); ++i)
cout<<outL[i]<<" ";
cout<<endl;
}
if(!a.empty()){
stac.push(a.top());
a.pop();
finn();
a.push(stac.top());
stac.pop();
}
if(!stac.empty()){
outL.push_back(stac.top());
stac.pop();
finn();
stac.push(outL[outL.size()-1]);
outL.pop_back();
}
}
int main(){
a.push('a');
a.push('b');
a.push('c');
a.push('d');
finn();
return 0;
}