#leetcode-力扣 组合综合类型题总结
今天回头看作过的题,还是要总结一下才好真正记住,就总结一下吧,这四道题题目一样,来具体分析一下区别。
39. 组合总和
链接:https://leetcode-cn.com/problems/combination-sum
题目:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:
输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
def dfs(num, tmp, index):
if num == 0:
res.append(tmp)
for i in range(index, len(candidates)):
if candidates[i] > num:
break
dfs(num-candidates[i], tmp+[candidates[i]], i)
dfs(target,[], 0)
return res
40.组合总和 II
链接:https://leetcode-cn.com/problems/combination-sum-ii
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
def dfs(num, pre, index):
if num== 0:
res.append(pre)
for i in range(index, len(candidates)):
if candidates[i]>num:
break
##只能用一次数!!所以这里要判断排序后选择的数是否和前面一样,如果一样就不选了,同时要排除第一个数的情况。
if i > index and candidates[i]== candidates[i-1]:
continue
dfs(num-candidates[i], pre+[candidates[i]], i+1)
dfs(target, [], 0)
return res
216. 组合总和 III
链接:https://leetcode-cn.com/problems/combination-sum-iii
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。
解集不能包含重复的组合。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def dfs(num, pre, index):
if len(pre) == k and num == n:
res.append(pre)
if len(pre) < k:
for i in range(index, 10):
if num+i<=n:
dfs(num+i, pre+[i], i+1)
dfs(0,[],1)
return res
377. 组合总和 Ⅳ
链接:https://leetcode-cn.com/problems/combination-sum-iv
给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
示例:
nums = [1, 2, 3]
target = 4
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [0 for _ in range(target+1)]
dp[0]=1
# dp = [ for _ in range(len(nums)+1)]\[0 for _ in range(target+1)]
for i in range(target+1):
for num in nums:
if i >= num:
dp[i] += dp[i-num]
return dp[target]
- 这道题只需要计算种类的情况,不需要列出来,所以用dp即可。