# 简单的算法有关问题

www.MyException.Cn  网友分享于：2013-02-14  浏览：6次

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;
}
/*

123
132
213
231
321
312
*/

------解决方案--------------------

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;
}