LeetCode – Combination Sum IV (Java)

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 Solution

This problem is similar to Coin Change. It’s a typical dynamic programming problem.

public int combinationSum4(int[] nums, int target) {
    if(nums==null || nums.length==0)
        return 0;
 
    int[] dp = new int[target+1];
 
    dp[0]=1;
 
    for(int i=0; i<=target; i++){
       for(int num: nums){
           if(i+num<=target){
               dp[i+num]+=dp[i];
           }
       }
    }
 
    return dp[target];
}

1 thought on “LeetCode – Combination Sum IV (Java)”

  1. ‘if(i+num<=target)' shouldn't be: if (i + num <= target && i != num) ?
    For nums [3,4,5,6] and target 9, when i = 3 and num =3 the algorithm would say:
    dp[3+3] = dp[6] (=1 already from step i=0) + dp[3] (=1 already from step i=0)
    but dp[6] it's not 2, you can't have 2 combinations of nums that will get you to 6, knowing that elements are unique.

Leave a Comment