From 5eab2050cf9c1d419491f085796d7e788dfac317 Mon Sep 17 00:00:00 2001 From: Younglesszzz <571688981@qq.com> Date: Wed, 27 Oct 2021 20:03:18 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=A6=E4=B8=80=E7=A7=8D=E5=86=99=E6=B3=95?= =?UTF-8?q?=20=E5=85=A8=E6=8E=92=E5=88=97=E2=85=A1=20Java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...溯算法去重问题的另一种写法.md | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index d8125e91..8f5744b5 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -249,6 +249,45 @@ used数组可是全局变量,每层与每层之间公用一个used数组,所 Java: +**47.全排列II** + + +```java +class Solution { + private List> res = new ArrayList<>(); + private List path = new ArrayList<>(); + private boolean[] used = null; + + public List> permuteUnique(int[] nums) { + used = new boolean[nums.length]; + Arrays.sort(nums); + backtracking(nums); + return res; + } + + public void backtracking(int[] nums) { + if (path.size() == nums.length) { + res.add(new ArrayList<>(path)); + return; + } + HashSet hashSet = new HashSet<>();//层去重 + for (int i = 0; i < nums.length; i++) { + if (hashSet.contains(nums[i])) + continue; + if (used[i] == true)//枝去重 + continue; + hashSet.add(nums[i]);//记录元素 + used[i] = true; + path.add(nums[i]); + backtracking(nums); + path.remove(path.size() - 1); + used[i] = false; + } + } +} + +``` + Python: