public class Solution {
public static void backTrack(int[] nums, boolean[] used, List<Integer> tmp, List<List<Integer>> res) {
if (tmp.size() == nums.length) {
res.add(new ArrayList<>(tmp));
return;
}
else {
for (int i=0; i<nums.length; i++) {
if (used[i] || i>0 && nums[i-1]==nums[i] && !used[i-1]) continue;
used[i] = true;
tmp.add(nums[i]);
backTrack(nums, used, tmp, res);
used[i] = false;
tmp.remove(tmp.size()-1);
}
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums); // always sort when there are duplicates in the array
List<List<Integer>> res = new ArrayList<>();
backTrack(nums, new boolean[nums.length], new ArrayList<>(), res);
return res;
}
}
Leetcode 47. Permutations II
最新推荐文章于 2025-01-19 20:30:00 发布