您的位置:首页 > 其它

47. Permutations II

2016-03-08 10:59 351 查看
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].

//不懂 存在疑惑???
public class Solution {
List<List<Integer>> result = new ArrayList<List<Integer>>(); //先定义
public List<List<Integer>> permuteUnique(int[] nums) {

Arrays.sort(nums); //进行排序
permutefunc(nums,nums.length,new ArrayList<Integer>(),new HashSet<Integer>()); //使用了HashSet
return result;
}

public void permutefunc(int[] nums,int k,List<Integer> array,Set<Integer> chosen){

if(k==0){
result.add(new ArrayList(array));
return;
}
for(int i=0;i<nums.length;i++){
if(i>0&&nums[i]==nums[i-1]&&!chosen.contains(i-1))continue;
if(chosen.add(i)){
array.add(nums[i]);
permutefunc(nums,k-1,array,chosen);
array.remove(array.size()-1);
chosen.remove(i);
}
}
return;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: