【Python】回溯之组合问题
求组合问题,回溯剪枝,非常优秀
40. 组合总和 II
https://leetcode.cn/problems/combinationsumii/
思路:
求不重复的的全排列,首先确
https://leetcode.cn/problems/permutations-ii/
思路:
PS:path+[nums[i]]也可以这样写 path.append(nums[i]) backtracking() path.pop()
可以理解为,只把扩展后的path传入了递归,其本身没有改变,相当于加进去了又pop了
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
check = [0 for _ in range(len(nums))]
def backtracking(path):
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if check[i] == 1: continue
if i > 0 and nums[i] == nums[i-1] and check[i-1] == 0: continue
check[i] = 1
backtracking(path + [nums[i]])
check[i] = 0
backtracking([])
return res