第一种方法是用递归:多次调用函数可能会时间比较长,所以建议用库函数而不是递归
这里可以当做一个搜索来理解
五位数:当做数组来处理就好理解了
#include <stdio.h>
#include <string.h>
int array[10];
bool used[10];
const int n=5;
void print()
{
for(int i=1;i<=n;i++)
printf("%d",array[i]);
puts("");
}
void dfs(int index)
{
//-------------递归基--------------//
if(index==n+1){
print();
return ;
}
//--------------搜索---------------//
for(int i=1;i<=n;i++)
if(!used[i]){
array[index]=i;
used[i]=true;
dfs(index+1);
//下面是回溯
used[i]=false;
}
}
int main()
{
//freopen("out.txt","w",stdout);
memset(used,false,sizeof(used));
dfs(1);
return 0;
}
c++没有c好
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
sort(str.begin(), str.end());
cout << str << endl;
while (next_permutation(str.begin(), str.end()))
{
cout << str << endl;
}
return 0;
}
c代码
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX 100
using namespace std;
int main()
{
int length;
char str[MAX];
gets(str);
length = strlen(str);
//注意***需要排序
sort(str, str + length);
puts(str);
while (next_permutation(str, str + length))
{
puts(str);
}
return 0;
}
例题:
题目意思就是排序,但是有相同的不能重复出现
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
char a[205];
bool used[205];
char str[205];
int len;
void dfs(int index)
{
char last='\0';//不是全局变量(保证每一层相邻如果相同就不进行下去的,而不是全局变量)
if(index==len){
str[len]='\0';
puts(str);
return ;
}
for(int i=0;i<len;i++){
if(!used[i]&&a[i]!=last){//这里我的思路就是相邻的两个相同的就不能够递归下去,防止了相同的序列出现
str[index]=a[i];//注意是index,不是i,之前就是这个错误
used[i]=true;
last=a[i];
dfs(index+1);
used[i]=false;
}
}
}
int main()
{
while(gets(a))
{
len=strlen(a);
memset(used,false,sizeof(used));
sort(a,a+len);
dfs(0);
}
return 0;
}