1384 全排列(回溯)
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题


给出一个字符串S(可能有重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = "1312",
输出为:
1123
1132
1213
1231
1312
1321
2113
2131
2311
3112
3121
3211
Input
输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)
Output
输出S所包含的字符组成的所有排列
Input示例
1312
Output示例
1123 1132 1213 1231 1312 1321 2113 2131 2311 3112 3121 3211
Dfs 遍历出所有结果,string 数组存出结果, sort对结果进行排序,unique 对结果去重(去重之前需要排序)
#include <iostream> #include <algorithm> #include <string> #include <cstring> using namespace std; #define maxn 400000 string result[maxn]; char temp[maxn]; char original[maxn]; int numbers; int len; bool visit[maxn]; void Dfs(int x) { if (x == len) { temp[x] = '\0'; result[numbers++] = temp; return; } for (int i = 0; i < len; i++) { if (!visit[i]) { visit[i] = true; temp[x] = original[i]; Dfs(x + 1); visit[i] = false; } } } int main() { //cin >> original; while (cin >> original) { len = strlen(original); numbers = 0; memset(visit, false, sizeof(visit)); Dfs(0); sort(result, result + numbers); int m = unique(result, result + numbers) - result; // string 方法去重 for (int i = 0; i < m; i++) { cout << result[i] << endl; } } return 0; }