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)的问题
1 public class Solution { 2 /** 3 * @param nums an integer array and all positive numbers, no duplicates 4 * @param target an integer 5 * @return an integer 6 */ 7 public int backPackVI(int[] nums, int target) { 8 // Write your code here 9 int[] count = new int[target+1]; 10 count[0] = 1; 11 12 for(int i=1;i<=target;i++){ 13 for(int j=0;j<nums.length;j++){ 14 if(i-nums[j]>=0){ 15 count[i]+=count[i-nums[j]]; 16 } 17 } 18 } 19 return count[target]; 20 } 21 }