【LeetCode】#47全排列II(Permutations II)
阿新 • • 發佈:2018-12-06
【LeetCode】#47全排列II(Permutations II)
題目描述
給定一個可包含重複數字的序列,返回所有不重複的全排列。
示例
輸入: [1,1,2]
輸出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
Description
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
解法
class Solution { List<List<Integer>> res = new ArrayList<>(); public List<List<Integer>> permuteUnique(int[] nums) { if(nums.length==0){ return res; } Arrays.sort(nums); helper(new ArrayList<Integer>(), nums, new boolean[nums.length]); return res; } public void helper(List<Integer> list, int[] nums, boolean[] used){ if(list.size()==nums.length){ res.add(new ArrayList<>(list)); return ; } for(int i=0; i<nums.length; i++){ if(used[i] || (i!=0 && nums[i]==nums[i-1] && !used[i-1])){ continue; } used[i] = true; list.add(nums[i]); helper(list, nums, used); used[i] = false; list.remove(list.size()-1); } } }