Permutations
来源:互联网 发布:linux ftp 指定ip登录 编辑:程序博客网 时间:2024/05/20 21:22
题目名称
Permutations—LeetCode链接
描述
Given a collection of numbers, return all possible permutations.
For example, [1,2,3]
have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
分析
最简单的方法就是利用nextPermutation来生成下一个字典序,参考我的博客字典序—lexicographical order。
C++代码
/**************************************************************Copyright:武汉大学计算机学院B507Author: RyanDate:2015-11-4Description:Permutations**************************************************************/#include<iostream>#include<algorithm>#include<vector>using namespace std;void nextPermutation(vector<int>& nums);vector< vector<int> > permute(vector<int>& nums) { vector< vector<int> > res; int n = nums.size(); if(n==0) return res; vector<int> cur(nums); do{ res.push_back(cur); nextPermutation(cur); }while(cur!=nums); return res;}void nextPermutation(vector<int>& nums) { int size = nums.size(); if(size==0 || size==1) return; vector<int>::iterator p = nums.end()-1,q=nums.end()-1; while( p!=nums.begin() && *p<=*(p-1) ) p--; if(p==nums.begin()) reverse(nums.begin(),nums.end()); else if(p==nums.end()-1) swap(*p,*(p-1)); else{ p--; while(*q<=*p) q--; swap(*p,*q); reverse(p+1,nums.end()); } }int main() { int a[]={4,2,1,3}; vector<int> test(a,a+4); vector< vector<int> > res = permute(test); cout<<"["<<endl; for(int i=0;i<res.size();i++){ cout<<" "<<"["<<" "; for(int j=0;j<res[0].size();j++){ cout<<res[i][j]<<" "; } cout<<"]"<<endl; } cout<<"]"<<endl; return 0;}
总结
这个方法并不是最好的,但是字典序排列确实是一个很不错的方法,用来解决排列问题也未尝不可,我看到有写博客上说用DFS+swap的方法,我暂时还没有看懂。
0 0
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Xposed插件Android.EagleEye
- opencv学习篇(7)基本绘图
- 静态内部类和非静态内部类的区别
- IIC总线冲突??SEN只要置1,立即出现总线冲突!??
- Android内存溢出的相关问题
- Permutations
- flex TitleWindow 仿QQ窗口鼠标移动效果
- JPA 学习篇(二)搭建最简单的应用环境
- 网站写异常日志
- 使用Git上传本地项目到http://git.oschina.net
- jquery 图片延迟加载的实现
- Spring缓存注解@Cache使用
- notifition播放自定义声音
- .NET连接SQL Server的问题处理