Loading

Leetcode - 40. 组合总和 II

给定一个数组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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

(错误)解1 2021/9/6 O(?)

def help_recursion(l:list,v:int,ans:list)->bool:
    if v==0: return True
    len=l.__len__()
    if len==0: return False
    if len==1:
        if l[0]==v:
            ans.append(v)
            return True
        else: return False
    else:
        i=0
        while i<len:
            if l[i]>v: i+=1
            else: break
        if i==len: return False
        # 遍历剩下的每个数,怎么遍历呢??
        for x in l[i:]:
            ans.append(l[i])
            return help_recursion(l[i+1:],v-l[i],ans)

def combinationSum2(candidates: list, target: int) -> list:
    # 看着是个递归的问题
    # 题目限制:1)1 <= candidates[i] <= 50;2)1 <= target <= 30
    # 去掉大于target的数,减小规模
    candidates.sort(key=lambda x:-x)
    len=candidates.__len__()
    if candidates[0]>target:
        i=0
        while i<len:
            if candidates[i]>target: i+=1
            else: break
        candidates=candidates[i:]
    print(candidates)
    res=[]
    for i,v in enumerate(candidates):
        ans=[v]
        if help_recursion(candidates[i:],target-v,ans):
            res.append(ans)
    return res

if __name__ == '__main__':
    print(combinationSum2([10,1,2,7,6,1,5],8))
    # print(combinationSum2([2,5,2,1,2],5))
posted @ 2021-09-03 09:28  wwcg2235  阅读(25)  评论(0)    收藏  举报