[leetcode-377-Combination Sum IV]
阿新 • • 發佈:2017-06-24
一維數組 chang gin .html arr bin ces osi ()
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?
思路:
參考自:http://www.cnblogs.com/grandyang/p/5705750.html
這道題的真正解法應該是用DP來做,解題思想有點像之前爬梯子的那道題Climbing Stairs,我們需要一個一維數組dp,其中dp[i]表示目標數為i的解的個數,然後我們從1遍歷到target,對於每一個數i,遍歷nums數組,如果i>=x, dp[i] += dp[i - x]。這個也很好理解,比如說對於[1,2,3] 4,這個例子,當我們在計算dp[3]的時候,3可以拆分為1+x,而x即為dp[2],3也可以拆分為2+x,此時x為dp[1],3同樣可以拆為3+x,此時x為dp[0],我們把所有的情況加起來就是組成3的所有情況了,參見代碼如下:
int combinationSum4(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); vector<int>dp(target+1,0); dp[0] = 1; for (int i = 1; i <= target;i++) { for (int a : nums) { if (i<a)break;//a排序後只能越來越大 i>=a才有意義 否則提前結束內部循環 dp[i] += dp[i - a]; } } return dp[target]; }
[leetcode-377-Combination Sum IV]