您的位置:首页 > 其它

LeetCode Permutations II

2015-09-27 12:41 351 查看
原题链接在这里:https://leetcode.com/problems/permutations-ii/

题目:

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2]
have the following unique permutations:
[1,1,2]
,
[1,2,1]
, and
[2,1,1]


题解:

Permutations的进阶题目。但是nums中有重复元素,为了避免加重复值,需要去重。

去重的方法有两种,一个是加结果之前用contains看是否有重复结果,另外一个是找结果之前比较它是否与前一个元素相同。

Recursion方法和Permutations相同,但为了去重,不但需要比较与之前元素是否相同,还需要看之前元素是否被use过, 若果usd[i-1] = true 那么没有关系。

但若之前元素没有被用过那么就需要跳过了。

AC Java:

public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0){
return res;
}
boolean [] used = new boolean[nums.length];
Arrays.sort(nums);
helper(nums,used,new ArrayList<Integer>(), res);
return res;
}
private void helper(int[] nums, boolean [] used, List<Integer> item, List<List<Integer>> res){
if(item.size() == nums.length){
res.add(new ArrayList<Integer>(item));
return;
}
for(int i = 0; i < nums.length; i++){
if(i>0 && nums[i]==nums[i-1] && !used[i-1]){
continue;
}
if(!used[i]){
used[i] = true;
item.add(nums[i]);
helper(nums,used,item,res);
used[i] = false;
item.remove(item.size()-1);
}
}
}
}


Iteration方法和Subsets II很像,加进newRes之前检查newRes是否包含了重复item, 没有重复才可以加进来。

AC Java:

public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0){
return res;
}
List<Integer> item = new ArrayList<Integer>();
item.add(nums[0]);
res.add(item);
for(int i = 1; i<nums.length; i++){
List<List<Integer>> newRes = new ArrayList<List<Integer>>();
for(int j = 0; j<res.size(); j++){
List<Integer> cur = res.get(j);
for(int k=0;k<cur.size()+1;k++){
item = new ArrayList<Integer>(cur);
item.add(k,nums[i]);
if(!newRes.contains(item)){
newRes.add(item);
}
}
}
res = newRes;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: