LeetCode 47. Permutations II (全排列 II)
题目标签:Backtracking
利用dfs,建立一个 tempList, 递归加入每一个数字,利用 boolean[] used 来跳过 用过的数字,还有跳过重复的组合。
具体看code。
Java Solution:
Runtime: 1 ms, faster than 99.60 %
Memory Usage: 41.7 MB, less than 11.94 %
完成日期:11/08/2019
关键点:建立 boolean[] used
class Solution { List<List<Integer>> res; public List<List<Integer>> permuteUnique(int[] nums) { res = new ArrayList<>(); List<Integer> tempList = new ArrayList<>(); boolean[] used = new boolean[nums.length]; Arrays.sort(nums); DFS(nums, tempList, used); return res; } private void DFS(int[] nums, List<Integer> tempList, boolean[] used) { if(tempList.size() == nums.length) { res.add(new ArrayList<>(tempList)); return; } for(int i=0 ; i<nums.length; i++) { if(used[i]) continue; if(i>0 && nums[i-1] == nums[i] && !used[i-1]) // if it is a duplicated permutation, skip continue; used[i] = true; tempList.add(nums[i]); DFS(nums, tempList, used); used[i] = false; tempList.remove(tempList.size() - 1); } } }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/