[leedcode 46] Permutations
2015-07-11 11:03
239 查看
Given a collection of numbers, return all possible permutations.
For example,
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].
public class Solution { //全排列:构造一个递归函数,函数的参数一个代表开始排列的索引,一个代表最终排列的索引 //每一位与开始位进行交换,再递归start+1到end,注意结果的保存 List<Integer> seq; List<List<Integer>> res; public List<List<Integer>> permute(int[] nums) { seq=new ArrayList<Integer>(); res=new ArrayList<List<Integer>>(); findpermute(nums,0,nums.length-1); return res; } public void findpermute(int []nums,int start,int end){ if(start>end){ res.add(new ArrayList<Integer>(seq));//注意要重新new一个 return ; } for(int i=start;i<=end;i++){ swap(nums,start,i); seq.add(nums[start]); findpermute(nums,start+1,end); seq.remove(seq.size()-1);//注意删除 swap(nums,start,i); } } public void swap(int[] nums,int i,int j){ int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } }
相关文章推荐
- java接口 笔记
- struct、union、enum and sizeof
- javascript 学习笔记(权威指南)
- liferay初体验
- Docker-2.容器有关
- 养生保健常识
- java内部类
- java持有对象
- HDU 4790 Just Random
- [办公自动化]skydrive onedrive
- Yii 日志组件
- 深入理解C++的const变量
- * linux下编译,链接,运行,汇编程序
- Class.forName()详解
- jquery 创建遮盖层 示例代码
- WPF DataGrid导出到Excel
- htm5
- linux内核代码风格
- 文件2
- 苹果开建香港第四家零售店 或为亚洲最大