No.47 Permutations II
47. 全排列 II - 力扣(LeetCode) (leetcode-cn.com)
重点在于理解去重的表达式
思路:先排序,保证相同的数字放在一起。
接着按照回溯算法的步骤写, 需要注意的点在于如何避免同一层的重复。
设置一个boolean[]数组,记录一种排列中是否只用过,避免出现同一个数(不是相等的数)在一个排列中出现两次
然后在同一层的节点之间,boolean[i-1]应当是未使用过的
class Solution { public List<List<Integer>> permuteUnique(int[] nums) { int len = nums.length; List<List<Integer>> res = new ArrayList<>(); Deque<Integer> path = new ArrayDeque<>(); boolean[] used = new boolean[len]; //当前的path中使用过的序号,从深度的顺序设置,同一层的算是未使用过的 Arrays.sort(nums); backtrack(nums, res, path, used, 0); return res; } public void backtrack(int[] nums, List<List<Integer>> res, Deque<Integer>path, boolean[] used, int curIdx){ int len = nums.length; if(path.size() == len){ res.add(new ArrayList<>(path)); return; } for(int i=0; i<len; i++){ if(i>0 && nums[i]==nums[i-1] && !used[i-1] ){ continue; } if(!used[i]){ path.addLast(nums[i]); used[i] = true; backtrack(nums, res, path, used, i); used[i] = false; path.removeLast(); } } } }

浙公网安备 33010602011771号