标签:highlight 问题 example end turn notice tin ons 去重
给定一个候选数字的集合 candidates
和一个目标值 target
. 找到 candidates
中所有的和为 target
的组合.
在同一个组合中, candidates
中的某个数字不限次数地出现.
样例 1:
输入: candidates = [2, 3, 6, 7], target = 7
输出: [[7], [2, 2, 3]]
样例 2:
输入: candidates = [1], target = 3
输出: [[1, 1, 1]]
target
) 都是正整数.class Solution: """ @param candidates: A list of integers @param target: An integer @return: A list of lists of integers """ def combinationSum(self, candidates, target): # write your code here result = [] self.dfs(sorted(list(set(candidates))), target, result, path=[], start_index=0) return result def dfs(self, nums, target, result, path, start_index): if target == 0 and path: result.append(list(path)) if target < 0: return for i in range(start_index, len(nums)): path.append(nums[i]) self.dfs(nums, target-nums[i], result, path, i) path.pop()
给定一个数组 num
和一个整数 target
. 找到 num
中所有的数字之和为 target
的组合.
样例 1:
输入: num = [7,1,2,5,1,6,10], target = 8
输出: [[1,1,6],[1,2,5],[1,7],[2,6]]
样例 2:
输入: num = [1,1,1], target = 2
输出: [[1,1]]
解释: 解集不能包含重复的组合
num
中的每一个数字仅能被使用一次.target
) 都是正整数.class Solution: """ @param num: Given the candidate numbers @param target: Given the target number @return: All the combinations that sum to target """ def combinationSum2(self, nums, target): # write your code here result = [] self.dfs(sorted(nums), target, result, path=[], start_index=0) return result def dfs(self, nums, target, result, path, start_index): if target == 0 and path: result.append(list(path)) if target < 0: return for i in range(start_index, len(nums)): if i > 0 and nums[i] == nums[i-1] and i > start_index: continue path.append(nums[i]) self.dfs(nums, target-nums[i], result, path, i+1) path.pop()
dfs --path sum 问题 本质上就是组合问题(有去重)
标签:highlight 问题 example end turn notice tin ons 去重
原文地址:https://www.cnblogs.com/bonelee/p/11668915.html