47. 全排列 II
阿新 • • 發佈:2020-07-19
給定一個可包含重複數字的序列,返回所有不重複的全排列。
示例:
輸入: [1,1,2]
輸出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/permutations-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。 思路: 參考46題 本題還要額外考慮剪枝 去除重複結果 當只要遇到起點一樣,就有可能產生重複。 還要考慮不同深度情況下,11′2不應該誤剪
示例:
輸入: [1,1,2]
輸出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/permutations-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。 思路: 參考46題 本題還要額外考慮剪枝 去除重複結果 當只要遇到起點一樣,就有可能產生重複。 還要考慮不同深度情況下,11′2不應該誤剪
1 public List<List<Integer>> permuteUnique(int[] nums) { 2 int length = nums.length; 3 if (length == 0) return null; 4 Stack<Integer> path = new Stack<>();//容器 5 boolean[] used = new boolean[length];//記錄該數字是否加入容器中 6 int depth = 0;//深度 7 List<List<Integer>> ans = new ArrayList<>();//答案 8 Arrays.sort(nums);//排序 9 10 arrary(nums, length, depth, used, path, ans); 11 return ans; 12 } 13 14 private void arrary(int[] nums, int length, int depth, boolean[] used, Stack<Integer> path, List<List<Integer>> ans) { 15 if (depth == length) {16 ans.add(new ArrayList<>(path)); 17 return; 18 } 19 20 for (int i = 0; i < length; i++) { 21 if (used[i]) continue; 22 //剪枝 去除重複結果 23 //used[i] == used[i - 1] 如果這次選取數字與同深度的上次選取數字一樣 則後面排序有可能重複 如Aa... 與 aA...排序結果必然一樣 24 //used[i - 1] == false 為了排除不同深度情況下 相同數字的樹枝不被誤剪 如Aab 在選取Aa時不應該因為Aa相同而剪掉Aab樹枝 25 if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) continue; 26 27 used[i] = true; 28 path.push(nums[i]); 29 30 arrary(nums, length, depth + 1, used, path, ans); 31 32 used[i] = false; 33 path.pop(); 34 } 35 }
詳細檢視https://leetcode-cn.com/problems/permutations-ii/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liwe-2/