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];
    for(int i=0; i<=target; i++){
       for(int num: nums){
    return dp[target];
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Ionut Mandra

    ‘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.