leetcode回溯法,给定重复元素,求出不重复的集合
class Solution { List<List<Integer>> lists = new ArrayList<List<Integer>>(); LinkedList<Integer> list = new LinkedList<Integer>(); boolean[] used; public List<List<Integer>> permuteUnique(int[] nums) { if(nums.length == 0) return lists; Arrays.sort(nums); used = new boolean[nums.length]; backTracking(nums); return lists; } public void backTracking(int[] nums){ if(list.size() ==nums.length) lists.add(new ArrayList<Integer>(list)); for(int i =0;i<nums.length;i++){ // 条件1不能重复选取同一个元素 if(used[i]){ continue; } // 条件2同树层不能选取相同的元素 但是同树枝可以选取同一个元素 if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) { continue; } list.add(nums[i]); used[i] = true; backTracking(nums); list.removeLast(); used[i] = false; } } }
需要注意 全排列问题为什么不用startIndex?