• [LeetCode]题解(python):039-Combination Sum



    题目来源


    https://leetcode.com/problems/combination-sum/

    Given a set of candidate numbers (C) 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.


    题意分析


    Input: a list as candidates, a value named target

    Output:the list number that sumed to target

    Conditions:在list里面找若干个数,使得和为target,注意每个数可以取若干次

    Note:

    • All numbers (including target) will be positive integers.
    • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    • 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] 


    题目思路


    先对list进行排序,然后穷举即可


    AC代码(Python)

     1 _author_ = "YE"
     2 # -*- coding:utf-8 -*-
     3 
     4 class Solution(object):
     5     def find(self,candidates, target, start, valueList):
     6         if target == 0:
     7             Solution.ans.append(valueList)
     8         length = len(candidates)
     9         for i in range(start, length):
    10             if candidates[i] > target:
    11                 return
    12             self.find(candidates, target - candidates[i], i, valueList + [candidates[i]])
    13 
    14     def combinationSum(self, candidates, target):
    15         """
    16         :type candidates: List[int]
    17         :type target: int
    18         :rtype: List[List[int]]
    19         """
    20         candidates.sort()
    21         Solution.ans = []
    22         self.find(candidates, target, 0, [])
    23         return Solution.ans
    24 
    25 s = Solution()
    26 candidates = [2,3,6,7]
    27 target = 7
    28 print(s.combinationSum(candidates, target))
  • 相关阅读:
    jdbc之存储过程的调用和调用方法
    jdbc之Statement和Preparement
    jdbc之连接Oracle的基本步骤
    Oracle之子程序(存储过程、方法、包)
    Oracle之plsql及游标
    Oracle之多表查询
    Oracle之单表查询及常用函数
    Oracle之基础操作
    IO流之字符流
    IO流之字节流
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5025742.html
Copyright © 2020-2023  润新知