zoukankan      html  css  js  c++  java
  • [leetcode]39. Combination Sum

    Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    The same repeated number may be chosen from C unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    For example, given candidate set [2, 3, 6, 7] and target 7
    A solution set is: 

    [
      [7],
      [2, 2, 3]
    ]

    求所有和为target的可能组合,每个数可以出现多次

    思路:DFS,每加入一个值,继续向下遍历别的值,符合条件,加入结果

     1 class Solution(object):
     2     def combinationSum(self, candidates, target):
     3         if not candidates or not target:
     4             return []
     5         res,ress = [],[]
     6         self.dfs(sorted(candidates),target,res,ress)
     7         return ress
     8     
     9     def dfs(self,nums,target,res,ress):
    10         if target < 0: return
    11         if target==0:
    12             ress.append(res)
    13         else:
    14             for i,v in enumerate(nums):
    15                 if v <= target:
    16                     self.dfs(nums[i:],target-v,res+[v],ress)
    17         return 
  • 相关阅读:
    IO模型详解
    Java中的CAS实现原理
    深入理解幂等性
    区块链基本原理入门
    通俗易懂讲解IO模型
    java高级特性(4)--枚举
    static、final和finalize详解
    锁(3)-- DB锁
    浅析项目中的并发
    分布式(1)-- 分布式锁
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6551470.html
Copyright © 2011-2022 走看看