您的位置:首页 > 其它

LeetCode46 Permutations

2017-07-03 19:10 369 查看

原题:

英:

Given a collection of distinct numbers, return all possible permutations.

For example,

[1,2,3] have the following permutations:

中:

英:给定一组不同的数据,返回所有可能的排列。

例如,1,2,3有以下排列:

[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]


解题思路:

全排列问题,第一反应是用递归解决,感觉过程与39题也很类似。代码如下:

public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList();
List<Integer> add = new ArrayList<Integer>();
permuteRecursion(res, add, nums);
return res;
}

private void permuteRecursion(List<List<Integer>> res, List<Integer> add,
int[] nums) {
if(add.size()==nums.length){
List<Integer> tmp = new ArrayList<Integer>(add);
res.add(tmp);
}
for(int i=0;i<nums.length;i++){
if(!add.contains(nums[i])){
add.add(nums[i]);
permuteRecursion(res, add, nums);
add.remove(add.size()-1);
}else{continue;}
}

}
}


重点说明:

1.与39题类似,res在添加的时候也要使用临时变量。

2.判断添加的条件:add的size和nums的长度一样。

3.由于是全排列,nums里的值只用一次,所以在添加的时候要用add.contains(nums[i])判断add里面是否已经添加当前数值。

4.最后依然要用add.remove(add.size()-1)去掉最后添加的nums值,以尝试不同的组合。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode