• Combination Sum IV


    #Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive #integer target.

    #Example:

    #nums = [1, 2, 3]
    #target = 4

    #The possible combination ways are:
    #(1, 1, 1, 1)
    #(1, 1, 2)
    #(1, 2, 1)
    #(1, 3)
    #(2, 1, 1)
    #2, 2)
    #(3, 1)

    #Note that different sequences are counted as different combinations.

    #Therefore the output is 7.

    #类似走楼梯:nums = [1,2,3], target = 4
    #1有一种组合,2有两种组合,3有四种组合((-1后的组合)+ (-2后的组合)+ 本身正好-3 == 0)=1的组合+2的组合+1)
    #同理,4的组合 = (4-1)的组合 + (4-2)的组合 + (4-3)的组合 = 1+2+4 = 7
    #用递归写虽然很简单,但是递归的时间复杂度真的很垃圾,能不用尽量不用吧
    class Solution(object):
        def combinationSum4(self, nums, target):
            nums, combs = sorted(nums), [1] + [0] * (target)
            for i in range(target + 1):
                for num in nums:
                    if num  > i: break
                    if num == i: combs[i] += 1
                    if num  < i: combs[i] += combs[i - num]
            return combs[target]

  • 相关阅读:
    String,StringBuffer,StringBuilder简单对比
    Java基本数据类型
    EasyMock框架的使用详解
    Python3.6在win7中无法正常运行的问题
    zabbix3.4源码安装步骤
    hadoop_2.6.5集群安装
    Cassandra2.2.10安装过程
    JDK1.8安装
    zookeeper3.4.6安装
    python3.6的安装及cx_oracle安装
  • 原文地址:https://www.cnblogs.com/phinza/p/10306988.html
Copyright © 2020-2023  润新知