給定一個可包含重復數字的序列,返回所有不重復的全排列。
示例:
輸入: [1,1,2]
輸出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
代碼
class Solution {List<List<Integer>> cList=new ArrayList<>();public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);//排序,將重復元素排在一起permute(nums,new ArrayList<>(),new boolean[nums.length]);return cList;}public void permute(int[] nums,List<Integer> temp,boolean[] check) {if(temp.size()==nums.length){cList.add(new ArrayList<>(temp));return;}for(int i=0;i<nums.length;i++)//可能的選擇{if(check[i]) continue;//已經遍歷了if(i>0&&nums[i]==nums[i-1]&&!check[i-1]) continue;//重復元素temp.add(nums[i]);check[i]=true;permute(nums,temp,check);check[i]=false;//回溯temp.remove(temp.size()-1);}}
}