首页 > 其他 > 详细

51nod 1384 全排列

时间:2018-10-09 00:13:49      阅读:190      评论:0      收藏: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,选择每一位的数字,因为有重复的,为避免重复,循环时,需判断后面若有相同的应当跳过。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

char s[10],t[10];
int len;
bool vis[10];
void dfs(int k) {
    if(k >= len) {
        printf("%s\n",t);
        return;
    }
    for(int i = 0;i < len;i ++) {
        if(!vis[i]) {
            vis[i] = true;
            t[k] = s[i];
            dfs(k + 1);
            vis[i] = false;
            while(s[i + 1] && s[i + 1] == s[i]) i ++;
        }
    }
}
int main() {
    scanf("%s",s);
    len = strlen(s);
    t[len] = 0;
    sort(s,s + len);
    dfs(0);
}

 

51nod 1384 全排列

原文:https://www.cnblogs.com/8023spz/p/9757769.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!