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.
分析
这一题如果使用递归的办法去解得话会超时,那么将就只能使用动态规划的办法去解决。
dp[i] = dp[i-nums[0]] + dp[i-nums[1]] + .... + dp[i-nums[j]] + .... (if i - nums[j] >= 0)
但是在测试的时候发现[3, 33, 333], 10000这个测试集会报 overflow,原因是在计算中间的结果的时候,导致了dp[i]超过了int的大小,使用long long也有同样的问题,但是由于最终结果是int能够表示的,说明这些中间结果一定是用不上的,所以直接改成unsigned int 即可,unsigned int 在超过后会归0.
Code
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
int length = nums.size();
if (length == 0)
return 0;
vector<unsigned int> dp(target +1, 0);
dp[0] = 1;
for (int i = 1; i <= target; i ++)
{
for (int m = 0; m < nums.size(); m ++)
{
if (i - nums[m] < 0)
continue;
dp[i] += dp[i - nums[m]];
}
}
return dp[target];
}
};
运行效率
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Combination Sum IV.
Memory Usage: 8.7 MB, less than 74.19% of C++ online submissions forCombination Sum IV.