leetcode--Permutations
2015-06-06 15:28
423 查看
Given a collection of numbers, return all possible permutations.
For example,
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
solve(nums, 0, res);
return res;
}
public void solve(int[] nums,int i,List<List<Integer>> res){
if(i==nums.length-1){
List<Integer> t = new ArrayList<Integer>();
for(int j=0;j<nums.length;j++){
t.add(nums[j]);
}
res.add(t);
}
for(int j=i;j<nums.length;j++){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
solve(nums, i+1, res);
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
}
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 {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
solve(nums, 0, res);
return res;
}
public void solve(int[] nums,int i,List<List<Integer>> res){
if(i==nums.length-1){
List<Integer> t = new ArrayList<Integer>();
for(int j=0;j<nums.length;j++){
t.add(nums[j]);
}
res.add(t);
}
for(int j=i;j<nums.length;j++){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
solve(nums, i+1, res);
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
}
相关文章推荐
- Linux磁盘配额
- centos7 光盘本地yum源
- mongoDB数据库验证登陆及问题
- leetcode--Contains Duplicate II
- AngularJS实现购物车
- linux中使用内存映射(mmap)操作文件的方法
- MATLAB新手教程
- 配置mysql5.5主从服务器(转)
- 十分钟让你明白Objective-C的语法(和Java、C++的对比)
- 茵茵的第一课
- 快速读取SharedPreferences数据
- Rust基础笔记之浅谈Ownership
- WINCE 6.0 输入法添加
- 世界需要程序员
- Android 部分属性学习
- Android 学习笔记 Service服务与远程通信...(AIDL)
- JavaScript 运行机制详解:再谈Event Loop
- 设计模式-工厂模式
- Codeforces Round #306 (Div. 2) B. Preparing Olympiad
- 每日一得-20150606