输入 abbccc abc (字符分别来自上面一个string) 输出 0,1,3 0,1,4 0,1,5 0,2,3 0,2,4 0,2,5 要求非递归 #include <iostream> #include <cstdio> #include <cstdlib> #include <string.h> #include <Windows.h> #include <string> #include <list> #include <vector> #include <stack> #include <fstream> using namespace std; string s1,s2; vector<vector<unsigned> > charPos; vector<int> sequence; void solve(int index) { if (index>=s2.size()) { for (int i=0;i<sequence.size();i++) { cout << sequence[i] << '/t'; } cout << endl; } else { char c=s2[index]; for (int i=0;i<charPos[c].size();i++) { sequence[index]=charPos[c][i]; solve(index+1); } } } int main() { charPos.resize(128); cin >> s1 >> s2; for (int i=0;i<s1.size();i++) { charPos[s1[i]].push_back(i); } sequence.resize(s2.size()); //recursive //solve(0); //树的每一层上各结点的孩子分枝数是相等的 //abbccc,abc //则第一层分枝数1(1个a),第二层分枝数2(2个b),第三层分枝数3(3个c[即对每个b有3个c可选]) //non-recursive int depth=s2.size(); //tree depth stack<int,vector<int> > st; //用vector方便查st[i]的值 st.push(0); //0 means the frist branch of the root while(1) { if (st.size() < depth) { st.push(0); } else //全排列形式的树的深度一致,深度达到时输出 { //output for (int i=0;i<depth;i++) { //即st[i] int b=*(&st.top()-st.size()+1+i); cout << charPos[s2[i]][b] << '/t'; } cout << endl; // while(!st.empty()) //not empty,loop until finding the node that has branches not visited yet { //has branches not visited yet(0-based) if (st.top()+1 < charPos[s2[st.size()-1]].size()) { ++st.top(); break; } else //return parent st.pop(); } if (st.empty()) //empty indicates no more branches to search for { //the 1st level of the tree,so terminate break; } } } system("pause"); return 0; }