zoukankan      html  css  js  c++  java
  • Leetcode-39-Submission Details (Medium)

    1、首先对数组进行排序

    2、递归搜索符合的元素

    3、注意回溯

    超越67%的用户

    #!/usr/local/bin/python3
    # -*- coding: utf-8 -*-
    __author__ = 'author'
    
    import copy
    class Solution(object):
    
        def __init__(self):
            self.result = []
    
        def combinationSum(self, candidates, target):
            """
            :type candidates: List[int]
            :type target: int
            :rtype: List[List[int]]
            """
    
            candidates.sort(reverse = True)
            return self.search_combinationSum(candidates, 0, [], 0, target)
    
    
        def search_combinationSum(self, candidates, index, tempRet, tempSum, target):
    
            #递归终止条件
            if target == tempSum:
                self.result.append(copy.deepcopy(tempRet))
                return
            elif target < tempSum:
                return
    
            for i in range(index, len(candidates)):
                if tempSum + candidates[i] <= target:
                    tempRet.append(candidates[i])
                    tempSum = tempSum + candidates[i]
                    self.search_combinationSum(candidates, i, tempRet, tempSum, target)
                    #回溯
                    del tempRet[len(tempRet) - 1]
                    tempSum = tempSum - candidates[i]
            return self.result
    
    
    if __name__ == '__main__':
        s = Solution()
        print(s.combinationSum([2, 6, 3, 7], 7))
    

      

  • 相关阅读:
    EntityManager 实例化方法
    Java Jpa 规范
    Spring HandlerInterceptor
    Spring data jpa
    Spring Security @PreAuthorize 拦截无效
    Java ee el表达式
    脏读&幻读
    OR查询是否会使得索引失效?
    ThinkPHP中的parseDSN方法的坑记录一下
    js , map中的坑
  • 原文地址:https://www.cnblogs.com/doudouyoutang/p/6290664.html
Copyright © 2011-2022 走看看