【Python】回溯之组合问题
求组合问题,回溯剪枝,非常优秀
40. 组合总和 II
https://leetcode.cn/problems/combinationsumii/
思路:
求不重复的的全排列,首先确
https://leetcode.cn/problems/combination-sum/
补上一个组合总数
思路:
没什么难度,hint:遇到回溯画个图,一个图不行,就画两个图
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
n = len(candidates)
def backtracking(path, rest, startIndex):
if rest < 0:
return
if rest == 0:
ans.append(path[:])
return
for i in range(startIndex, n):
path.append(candidates[i])
backtracking(path, rest - candidates[i], i)
path.pop()
backtracking([], target, 0)
return ans