排列问题
来源:互联网 发布:mac更新flash插件 编辑:程序博客网 时间:2024/06/08 06:16
//参考博客:http://blog.csdn.net/yoer77/article/details/53458612http://blog.csdn.net/cpfeed/article/details/7376132http://blog.csdn.net/morewindows/article/details/7370155//* 递归+回溯(未去重) */#include <iostream>#include <cstring>using namespace std;void Perm(char s[],int k,int n){ if(k == n-1) { for(int i = 0; i < n ;i++) cout<<s[i]; cout<<endl;; } else { for(int i = k ; i < n; i++) { swap(s[k],s[i]); Perm(s,k+1,n); swap(s[k],s[i]); } }}int main(){ char s[] = "123"; int len = strlen(s); Perm(s,0,len); return 0;}/* 递归+回溯(去重) */#include <iostream>#include <cstring>using namespace std;int count = 0;bool IsSwap(char s[],int l,int r){ for(int i = l ; i < r; i++) { if(s[i] == s[r]) return false; } return true;}void Perm(char s[],int k,int n){ if(k == n-1) { for(int i = 0; i < n; i++) cout<<s[i]; count++; cout<<endl; } else { for(int i = k; i < n; i++) { if(IsSwap(s,k,i)) { swap(s[k],s[i]); Perm(s,k+1,n); swap(s[k],s[i]); } } }}int main(){ char s[] = "1232"; int len = strlen(s); Perm(s,0,len); cout<<count<<endl; return 0;}/* dfs深搜(未去重) */#include <iostream>#include <cstring>using namespace std;#define maxn 100char perm[maxn];int visit[maxn];char s[] = "abcd";int count = 0;void dfs(int step,int n){ if(step == n) { for(int i = 0; i < n; i++) cout<<s[perm[i]]; count++; cout<<endl; } else { for(int i = 0; i < n; i++) { if(!visit[i]) { perm[step] = i; visit[i] = 1; dfs(step+1,n); visit[i] = 0; } } }}int main(){ int n = strlen(s); memset(perm,0,sizeof(perm)); memset(perm,0,sizeof(visit)); dfs(0,n); cout<<count<<endl; return 0;}/* 字典序 */#include <iostream>#include <cstring>using namespace std;void Reverse(char *i,char *j){ while(i < j) { swap(*i,*j); i++; j--; }}bool Next_permutation(char s[]){ int len = strlen(s); if(!len) return false; char *pEnd,*p,*q,*pFind; pEnd = s + len-1; p = pEnd; while(p != s) { q = p; p--; while(*p < *q) { pFind = pEnd; if(*pFind < *p) pFind--; swap(*p,*pFind); Reverse(q,pEnd); return true; } } Reverse(s,pEnd); return false;}int main(){ char s[] = "123"; do { cout<<s<<endl; }while(Next_permutation(s)); return 0;}
阅读全文
0 0
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- Golang实战【web服务器】
- CentOS 7 创建共享文件夹说明
- 优化分页查询
- springMVC注解@initbinder,表单中的日期 字符串和Javabean中的日期类型的属性自动转换
- 数据结构实验之图论九:最小生成树
- 排列问题
- 一键部署java web应用(linux)
- 计算机组成原理:运算方法和运算器
- 数据结构实验之图论十:判断给定图是否存在合法拓扑序列
- [LeetCode]718. Maximum Length of Repeated Subarray
- 通过maven将多模块项目一键部署到Tomcat上
- Win10 64bit下安装GPU版Tensorflow+Keras
- 自学编程的六个技巧总结
- 数据结构实验之图论十一:AOE网上的关键路径