Leetcode 377 Combination Sum IV

·

1 min read

Leetcode 377 Combination Sum IV

Problem Link - https://leetcode.com/problems/combination-sum-iv/description/

This DP Problem comes under Unbounded knapsack technique, where we are trying to get a certain sum with given numbers, and we can take any number as many times as we want.

Below is the decision tree for the choices for Example Input: nums = [1,2,3], target = 4

Green Circles are the choices that will lead to answers.

    public int combinationSum4(int[] nums, int T) {
        int[] dp = new int[T+1];

        // dp[0] means how many ways we can get the sum 0.
        dp[0] = 1;   

        // this outer for loop is to fill the dp array in bottom up manner
        for(int i=1 ; i<T+1; i++) { 
            // inner for loop to calculate how many ways to get this particular i(or sum) from all different numbers in nums array
            for(int j=0; j<nums.length; j++) {
                if(nums[j]<=i) {
                    dp[i] = dp[i] + dp[i-nums[j]];
                }
            }
        }
        return dp[T];
}