类型一:候选数组中的数可选可不选 (leetcode 40 组合总和)
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的每个数字在每个组合中只能使用一次。
输入: candidates = [10,1,2,7,6,1,5], target = 8
输出:[[1, 7],[1, 2, 5],[2, 6],[1, 1, 6]]
from typing import List
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
if len(candidates) < 1 or sum(candidates) < target:
return []
res = []
self.help(candidates, target, 0, res, [])
return res
def help(self, candidates, target, index, res, cur_list):
if target == 0:
cur_list.sort()
if cur_list not in res:
res.append(cur_list)
return
if index >= len(candidates):
return
self.help(candidates, target, index + 1, res, cur_list) # 不要当前候选
if target - candidates[index] >= 0:
self.help(candidates, target - candidates[index] , index + 1, res, cur_list+[candidates[index]])
if __name__ == '__main__':
candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8
a = Solution().combinationSum2(candidates, target)
print(a)
类型二:候选数组中的数都需要选,不过选择的顺序不同(leetcode 46、全排列 )
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
例如:
输入: [1,2,3]
输出:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
class Solution(object):
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
self.help(nums, res, [])
return res
def help(self, arr, res, cur_list):
if len(cur_list) == len(arr):
res.append(cur_list)
return
for num in arr:
if num not in cur_list:
self.help(arr, res, cur_list + [num])
if __name__ == '__main__':
arr = [1, 2, 3]
a = Solution().permute(arr)
print(a)