Easy to understand 4ms DP solution in Java


  • 0
    A
    public class Solution {
        public int combinationSum4(int[] nums, int target) {
            int[] dp = new int[target + 1];
            dp[0] = 1;//when current target exists in nums
    
            Arrays.sort(nums);
            
            for (int i = 1; i <= target; i++) {
                int sum = 0;
                for (int j = 0; j < nums.length && nums[j] <= i; j++) {
                    sum += dp[i - nums[j]];
                }
                dp[i] = sum;
            }
            
            return dp[target];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.