一.题目:
给定一个只包含正整数且不重复的数组nums,返回和为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.
二.解题思路:
一开始我们很容易想到用递归解题,但发现超时了.考虑这里只是需要得到解的个数,我们设计一个一维数组dp,其中dp[i]表示目标数为i的解的个数.代码如下:
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for i in xrange(1, target + 1):
for num in nums:
if i >= num:
dp[i] += dp[i - num]
return dp[-1]