简单的算法问题
给n个数,如何实现输出所有的组合结果?
比如3个数,应该输出
123
132
213
231
312
321
谢谢
[解决办法]
- C/C++ code
#include <iostream> #include <algorithm> using namespace std; template <class T> void prem(T list[],int k,int m) { int i; if(k==m) { for(i=0;i <=m;i++) cout << list[i]; cout << "\n"; } else for(i=k;i <=m;i++) { swap(list[k],list[i]); prem( list,k+1,m); swap(list[k],list[i]); } } int main() { ofstream file; file.open("test.txt"); char list[]={'1','2','3'}; int p=0,q=2; prem(list,p,q); file.close(); return 0; }
[解决办法]
mark
[解决办法]
http://blog.csdn.net/oeg2006/archive/2009/04/25/4119219.aspx
[解决办法]
可以用回溯法遍历排列树
- C/C++ code
#include <iostream>#include <string>using namespace std;int n = 0;string str = "";//交换void Swap(char &a,char &b){ char temp; temp = a; a = b; b = temp;}//递归回溯void Backtrack(int t){ if(t > n) //如果到达叶子节点则输出 { cout << str << endl; } else { for(int i = t; i <= n; i++) { Swap(str[t-1],str[i-1]); Backtrack(t + 1); Swap(str[i-1],str[t-1]); } }}int main(){ string str_in = ""; cout << "请输入数字:"; cin >> str_in; str = str_in; n = str_in.length(); Backtrack(1); return 0;}/*请输入数字:123123132213231321312*/
[解决办法]
不好意思^^~
看了三楼给的链接,发现又没考虑周全,没有考虑到重复的情况。
下面是加了判断重复条件的代码,希望这次的没有错了~
- C/C++ code
#include <iostream>#include <string>using namespace std;int n = 0;string str = "";//交换void Swap(char &a, char &b){ char temp; temp = a; a = b; b = temp;}//判断重复bool IsRepeat(int a, int b){ if(a != b) { if(str[a] == str[b]) { return false; } } return true;}//递归回溯void Backtrack(int t){ if(t > n) //如果到达叶子节点则输出 { cout << str << endl; } else { for(int i = t; i <= n; i++) { Swap(str[t-1],str[i-1]); if(IsRepeat(t-1,i-1))//判断是否有重复 { Backtrack(t + 1); } Swap(str[i-1],str[t-1]); } }}int main(){ string str_in = ""; cout << "请输入数字:"; cin >> str_in; str = str_in; n = str_in.length(); Backtrack(1); return 0;}