原题链接: https://leetcode.com/problems/combination-sum-iv/description/
原题: 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.
样例:
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.
Solution: 此题可以采用动态规划的解法,用combinations[i]表示用给定数组nums能组成i的方式数量。这样,combinations[0]就应为1,只要我们计算出combinations[target],那么它就是要求的解。
此问题的状态转移可表示为如下形式:
combinations[0] = 1;
combinations[i] = combinations[i - nums[0]] + combinations[i - nums[1]] + … + combinations[i - nums[n]]; 其中,i - nums[j]的大小必须大于等于0;
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
int n = nums.size();
int combinations[target+1];
combinations[0] = 0;
for (int i = 1; i <= target; i++) {
int sum = 0;
for (int j = 0; j < n; j++) {
if (i - nums[j] > 0) sum += combinations[i - nums[j]];
else if (i - nums[j] == 0) sum += 1;
}
combinations[i] = sum;
}
return combinations[target];
}
};
复杂度: 设数组nums的大小为n,那么此算法的时间复杂度为O(n * target),空间复杂度为O(target)。