我正在解决leetcode问题,我们必须找到可能增加到目标的集合数。
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.
我用Java编写了代码
JAVA
class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target+1];
dp[0] = 1;
for(int i = 1; i <= target; i++){
for(int num : nums){
if(i >= num){
dp[i] += dp[i-num];
}
}
}
return dp[target];
}
}
它通过了所有测试用例,但是当我用C ++编写相同的代码时。它失败了几个测试用例。
C ++
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
int dp[target+1] = {0};
dp[0] = 1;
for(int i = 1; i <= target; i++){
for(int num : nums){
if(i >= num){
dp[i] += dp[i-num];
}
}
}
return dp[target];
}
};
测试用例为:
nums : [3,33,333]
target : 10000
我得到的错误:
Line 9: Char 27: runtime error: signed integer overflow: 1941940377 + 357856184 cannot be represented in type 'int' (solution.cpp)
注:在代码中,您仅更改了dp数组部分的声明。为什么我会收到此错误。怎么了?
Java中的整数数组默认情况下将其所有元素初始化为零,C ++中不是这种情况。
在C ++中执行memset(dp,0,sizeof(dp));