Copy /*
递归的解法,超时
*/
public class Solution {
public int combinationSum4 ( int [] nums , int target) {
if (target == 0 ) {
return 1 ;
}
int res = 0 ;
for ( int i = 0 ; i < nums . length ; i ++ ) {
if (target >= nums[i]) {
res += combinationSum4(nums , target - nums[i]) ;
}
}
return res;
}
}
Copy public class Solution {
public int combinationSum4 ( int [] nums , int target) {
int [] dp = new int [target + 1 ];
Arrays . fill (dp , - 1 );
dp[ 0 ] = 1 ;
return helper(nums , dp , target) ;
}
private int helper ( int [] nums , int [] dp , int target) {
if (dp[target] != - 1 ) {
return dp[target];
}
int res = 0 ;
for ( int i = 0 ; i < nums . length ; i ++ ) {
if (target >= nums[i]) {
res += helper(nums , dp , target - nums[i]) ;
}
}
dp[target] = res;
return dp[target];
}
}
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?