Given an integer array nums
with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target
Example
Given nums = [1, 2, 4]
, target = 4
The possible combination ways are:
[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]
[2, 2]
[4]
return 6
一开始用backtracking 发现总是超时,后来网上找到的DP解法 简单有效。。类似于找钱(coin change)的问题
public class Solution {
/**
* @param nums an integer array and all positive numbers, no duplicates
* @param target an integer
* @return an integer
*/
public int backPackVI(int[] nums, int target) {
// Write your code here
int[] count = new int[target+1];
count[0] = 1; for(int i=1;i<=target;i++){
for(int j=0;j<nums.length;j++){
if(i-nums[j]>=0){
count[i]+=count[i-nums[j]];
}
}
}
return count[target];
}
}