From fd2608a38c99b2ff98130112c9c3a555b1be362d Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 27 May 2023 21:20:59 -0500 Subject: [PATCH] =?UTF-8?q?Update=200047.=E5=85=A8=E6=8E=92=E5=88=97II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0047.全排列II.md | 41 +++++++++++++++++------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index b4f7a4d8..de9b2bb4 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -208,28 +208,25 @@ class Solution { ```python class Solution: - def permuteUnique(self, nums: List[int]) -> List[List[int]]: - # res用来存放结果 - if not nums: return [] - res = [] - used = [0] * len(nums) - def backtracking(nums, used, path): - # 终止条件 - if len(path) == len(nums): - res.append(path.copy()) - return - for i in range(len(nums)): - if not used[i]: - if i>0 and nums[i] == nums[i-1] and not used[i-1]: - continue - used[i] = 1 - path.append(nums[i]) - backtracking(nums, used, path) - path.pop() - used[i] = 0 - # 记得给nums排序 - backtracking(sorted(nums),used,[]) - return res + def permuteUnique(self, nums): + nums.sort() # 排序 + result = [] + self.backtracking(nums, [], [False] * len(nums), result) + return result + + def backtracking(self, nums, path, used, result): + if len(path) == len(nums): + result.append(path[:]) + return + for i in range(len(nums)): + if (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]) or used[i]: + continue + used[i] = True + path.append(nums[i]) + self.backtracking(nums, path, used, result) + path.pop() + used[i] = False + ``` ### Go