码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 377. Combination Sum IV

时间:2017-01-05 07:54:13      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:change   bsp   number   class   duplicate   turn   limit   dup   mit   

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.

Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?

 

例子:[1,2,3,5,6], target = 8。dp[8] 意为有多少种方式可以生成8。

例如: 8=1(in nums) + 7 = 2(in nums) + 5 = 3(in nums) + 4= 5(in nums) + 3 = 6(in nums) + 2。 所以dp[8] = dp[7] + dp[5] + dp[4] + dp[3] + dp[2]。

        5=5(in nums) + 0 = 3(in nums) + 2 = 2(in nums) + 3 = 1(in nums) +4。 所以dp[5] = dp[0] + dp[2] + dp[4] + dp[4]。

 1 class Solution(object):
 2     def combinationSum4(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         dp = [0]*(target + 1)
 9         dp[0] = 1
10         for i in range(target+1):
11             for n in nums:
12                 if i + n <= target:
13                     dp[i+n] += dp[i]
14         return dp[-1]
15             

 

Leetcode 377. Combination Sum IV

标签:change   bsp   number   class   duplicate   turn   limit   dup   mit   

原文地址:http://www.cnblogs.com/lettuan/p/6250991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!