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?


 

其实第一反应想到的还是用深度优先搜索+回溯的方式来做,但这道题这样做感觉思路不太明显。拿例子来说,同样是加起来等于4,(1, 1, 2)和(1, 2, 1)和(2, 1, 1)都是不同的情况,也就是得到元素之后还要进行选择排列。这样的话是不是时间复杂度太高了呢?不会做。既然标签里提示了动态规划,那就想一想为什么会想到动态规划,以及状态转移方程到底是什么。

首先想为什么能用动态规划。其实这道题有点像LeetCode 322. Coin Change —— 零钱兑换。区别是322题求的是组成target最少需要多少数,而本题是求组成target所有情况的总数。按照322类似的思路,设dp[i]是target为i的组成总数,它要怎么从之前的状态得到。动态规划的题目里有些是可以从dp[i-1]得到,而有些要从dp[0] ~ dp[i-1]来得到。这道题便是后者。分析如下:

当target是0,即i是0的时候,理解上dp[0]应该是0,但是这里要设置成1,是因为要把这个1想象成空集去组合其他的数。感觉离散数学里某一节关于集合的内容一定是讲到类似的了,是时候复习下了…

当target是i,已知的是所有小于i的状态。那么dp[i-k],k是小于i的数,是全部都知道的。就像零钱兑换问题一样,每次的组合的变化都是因为选了不同的硬币/数字,所以dp[i-nums[j]]即以i-nums[j]作为target的时候所需要的组合数。这里注意和322题的区别。322需要dp[i-nums[j]] + 1来组成当前的金额,而本题不用,因为dp[i-nums[j]]里面存的是形成i-nums[j]这个target的组合数,多一个nums[j]从而使target变成i并不会使得组合数增加。相对的,322取的是不同nums[j]取值下的最小结果,而本题是不同的取法的组合总数。即随着nums[j]不同,dp[i]的值应该是考虑所有nums[j]后的总和。所以得到状态转移方程 dp[i] = dp[i] + dp[i-nums[j]]。对比两道题,代码几乎一样,除了本题不需要像322一开始dp数组需要置入一个比较大的值。

 


Java

class Solution {
    public int combinationSum4(int[] nums, int target) {
        if (nums == null || nums.length == 0 || target <= 0) return 0;
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int i = 1; i <= target; i++) 
            for (int j = 0; j < nums.length; j++) 
                if (i >= nums[j]) dp[i] += dp[i - nums[j]];
        return dp[target];
    }
}

 

posted on 2018-07-02 01:01  小T在学习  阅读(920)  评论(0编辑  收藏  举报