Problem
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.
Algorithm
整理一下题意:给定一个没有重复的正整数序列和一个目标整数,在序列中找到一个组合使得组合中所有数的和等于目标整数,要求返回满足要求的组合的数目。注意序列中的元素可以在组合中重复。
与无限背包问题类似,可以看作是给定容量在数组中选择元素的问题。状态转移方程为 f[i]=∑jf[i−nums[j]]
考虑一些具体的实现细节。对于初始化的问题,注意每个元素对应的nums[i]本身就构成f[nums[i]]的一种组合,故所有f[nums[i]]初始值应为1。但是由于nums元素的值可能比较大,而f数组的下标可能无法保证f[nums[i]]是有效语句,因此只对在f[i]数组长度内的nums[i]进行初始化。实际上从数学角度考虑,大于target的nums[i]也不能构成组合的一部分,不需要考虑。
代码如下。
//时间复杂度O(n^2)
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
int n=nums.size();
vector<int> f(target+1,0);
for(int i=0;i<n;i++)
if(nums[i]<=target)
f[nums[i]]=1;
for(int i=0;i<=target;i++){
for(int j=0;j<n;j++){
if(i-nums[j]>=0)
f[i]+=f[i-nums[j]];
}
}
return f[target];
}
};