leetcode 39. 组合总和 40. 组合总和 II
给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。
candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同,则两种组合是唯一的。
对于给定的输入,保证和为 target 的唯一组合数少于 150 个。
示例 1:
输入: candidates = [2,3,6,7], target = 7
输出: [[7],[2,2,3]]
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
示例 4:
输入: candidates = [1], target = 1
输出: [[1]]
示例 5:
输入: candidates = [1], target = 2
输出: [[1,1]]
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
candidates.sort()
def get_sum(s, ans_arr: List[int], tar):
nonlocal ans, target
if tar == 0:
ans.append(ans_arr.copy())
return
if tar < 0:
return
for i in range(s, len(candidates)):
if candidates[i] > tar:
return
ans_arr.append(candidates[i])
get_sum(i,ans_arr, tar - candidates[i])
ans_arr.pop()
get_sum(0, [], target)
return ans
if __name__ == '__main__':
candidates = [2,3,6,7]
candidates = [2,3,5]
candidates = [2,7,6,3,5,1]
target = 7
target = 8
target = 9
print(Solution().combinationSum(candidates, target))
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
提示:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
通过次数203,763提交次数327,393
from typing import List
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
arr = []
length = len(candidates)
if sum(candidates) < target:
return []
def get_sum(n, n_target, ans_arr: List[int]):
nonlocal arr, candidates, target, length
if n_target < 0:
return
if n_target == 0:
if ans_arr not in arr:
arr.append(ans_arr.copy())
return
valid = False
for i in range(n, length):
if valid and candidates[i] == candidates[i - 1]:
continue
if target - sum(ans_arr) < candidates[i]:
return
ans_arr.append(candidates[i])
get_sum(i + 1, n_target - candidates[i], ans_arr)
valid = True
ans_arr.pop()
get_sum(0, target, [])
return arr
if __name__ == '__main__':
candidates = [10, 1, 2, 7, 6, 1, 5]
# candidates = [2,5,2,1,2]
# candidates = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
# candidates = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
# 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
# 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
# candidates = [1, 1, 1, 1, 1, 1, 1]
target = 8
# target = 5
# target = 27
# target = 30
# target = 3
# print(len(candidates))
candidates = [3, 1, 3, 5, 1, 1]
target = 8
print(Solution().combinationSum2(candidates, target))