leetcode 377. Combination Sum IV
Posted 巴蜀小小生
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 377. 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.
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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
题目大意:找出数组中能组合成目标数的组合, 每个数字的使用次数不限
思路:用dp算法:从底到顶的计算,依次算出组合成1,2,3,4有多少种组合;
以上面的例子为例:【1,2,3】 target=4;
设置一个数组dp()来保存结果, dp[i]表示和为i的组合个数, 初始条件是dp[0]=1;
遍历数组如果当前的数num[j]比target小那么,只需知道 dp[target-num[j]] 就行了。相当于在和为target-nums[j]的组合后面构成了新的组合,满足和为target, 把所有满足nums[j]<target的dp[target-nums[j]]加起来就得到了target的组合;
dp的代码简洁,关键在于找到关系式
1 class Solution { 2 public: 3 int combinationSum4(vector<int>& nums, int target) { 4 int n=nums.size(),i,j; 5 int dp[target+1]={0}; 6 dp[0]=1; 7 for(i=1;i<=target;i++){ 8 for(j=0;j<n;j++){ 9 if(i >= nums[j]) 10 dp[i] += dp[i-nums[j]]; 11 } 12 } 13 return dp[target]; 14 } 15 };
以上是关于leetcode 377. Combination Sum IV的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 377. Combination Sum IV
[leetcode-377-Combination Sum IV]
LeetCode 377: Combination Sum IV