设有4个元素a,b,c,d进栈,给出他们所有可能的出栈次序。数据结构
这个结果我知道,但是我不知怎么用程序实现,哪位仁兄会?
[解决办法]
- C/C++ code
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;}
[解决办法]
[解决办法]
#include<iostream>
#include<stack>
using namespace std;
int count = 0;
template<class T>
void Create(stack<T> S, T tar[], T str[], int pos, int curp, int n)
{
if(pos < n) //还有元素没进栈则继续进栈
{
S.push(str[pos]); //进栈
Create(S, tar, str, pos+1, curp, n);
S.pop(); //出栈恢复环境
}
if(!S.empty()) //栈不为空则继续出栈
{
tar[curp] = S.top();//将出栈元素记录到目标数组中以待输出
S.pop(); //出栈
Create(S, tar, str, pos, curp+1, n);
S.push(tar[curp]); //进栈恢复环境
}
if(pos == n && S.empty()) //栈空且所有元素都进过栈则输出
{
tar[n] = '\0';
cout << "[" << ++count << "] " << tar << endl;
}
}
void main()
{
stack<char> S;
char str[6] = "12345";
char tar[6];
Create(S, tar, str, 0, 0, 5);
}
[解决办法]
不要用栈拉。这是个全排列问题吧?
- C/C++ code
#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 }