51nod:1384 全排列(dfs||c++函数)
来源:互联网 发布:散热分析中文软件 编辑:程序博客网 时间:2024/06/01 08:16
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示例
112311321213123113121321211321312311311231213211
李陶冶 (题目提供者)
C++的运行时限为:1000 ms ,空间限制为:131072 KB 示例及语言说明请按这里
解题思路:1.DFS+string的排序去重(string可以直接用sort来排序unique来去重)
#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <string>using namespace std;int size;char ans[15];char s[15];int visit[15];string o[400000];int cnt;void dfs(int n){if(n==size){ans[size]='\0';o[cnt++]=ans;return ;}for(int i=0;i<size;i++){if(visit[i]==0){ans[n]=s[i];visit[i]=1;dfs(n+1);visit[i]=0;}}}int main(){scanf("%s",s);cnt=0;size=strlen(s);sort(s,s+size);//这一步可以省略 memset(visit,0,sizeof(visit));dfs(0);sort(o,o+cnt);int m=unique(o,o+cnt)-o;//去重 for(int i=0;i<m;i++){cout<<o[i]<<endl;//string要用cout输出 }return 0;}
2.直接用c++的next_permutation函数可以直接做到全排列,不过用之前要sort下,然后输出本来的字符串,看代码参考下用法:
#include <cstdio>#include <algorithm>#include <cstring>#define MAX 100using 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;}
0 0
- 51nod:1384 全排列(dfs||c++函数)
- 51nod 1384 全排列 (dfs)
- 51nod 1384 全排列 (dfs/next_permutation)
- 51nod 1384 全排列(next_permutation函数)
- 51nod 1384 全排列(next_permutation()函数)
- 【51Nod】1384 - 全排列(STL)
- 51nod 1384 全排列(next_permutation)
- 51Nod-1384 全排列(回溯)
- 1384全排列【51NOD】
- 51NOD 1384 全排列
- 51nod 1384 全排列
- 51Nod--1384全排列
- 51NOD 1384 全排列
- 51nod 1384 全排列
- 51nod 1384全排列
- 51nod 1384 全排列
- 51nod 1384 全排列
- 51Nod 1384 全排列
- define和const常量的区别
- Android 编程下 Touch 事件的分发和消费机制
- 安卓界面组件---文版框
- H5_2_表单
- Target runtime Tomcat v7.0 is not defined.
- 51nod:1384 全排列(dfs||c++函数)
- 【数组】Leetcode编程题解:442. Find All Duplicates in an Array
- jQuery绑定键盘压下抬起事件
- 文章标题
- RegExp正则表达式(简单入门)
- composer的安装及配置
- 前端总结·基础篇·CSS(一)布局
- java实现网上在线支付--04_编写易宝支付的客户端加密工具类
- 重装系统win7让你惊呆下巴