题目1120:全排列
代码如下:
#include <stdio.h>
#include <string.h>
char str[7];
bool mark[7];
int n;
void DFS(char *ss, int len)
{
if (n == len)
{
ss[n] = '\0';
printf("%s\n", ss);
return;
}
for (int i = 0; i < n; i++)
{
if (!mark[i])
{
mark[i] = true; // 标记己访问
ss[len] = str[i];
DFS(ss, len + 1);
mark[i] = false; // 下一次递归时,str中i位置上的字符依然可用
}
}
}
int main()
{
while (scanf("%s", str) != EOF)
{
char ss[7];
n = strlen(str);
memset(mark, 0, n);
DFS(ss, 0);
printf("\n");
}
return 0;
}
STL解法:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
char str[7];
while (scanf("%s", str) != EOF)
{
int len = strlen(str);
do
{
puts(str);
} while (next_permutation(str, str + len)); // next_permutation求下一个排列,有:返回true,无:false
printf("\n");
}
return 0;
}
全排列相关博文:
[1] 字符串的全排列和组合算法
[2]【LeetCode】Permutations 解题报告