zoukankan      html  css  js  c++  java
  • [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))
  • 相关阅读:
    Hive和HBase的区别
    HBase面试问题
    HBase的rowkey的设计原则
    一、spark 数据类型(Data Types)
    Phaser显示对象(文字)
    Phaser中的组对象group
    Phaser中的动画
    phaser.js 显示对象笔记
    MD5之C#密码加密备忘录
    学了点小小的技巧,也有一点点问题,怎么解决呢?
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5025742.html
Copyright © 2011-2022 走看看