Algo-Sim › Dynamic Programming

Combination Sum IV

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Count the ordered sequences of numbers (reusable) that add up to a target: dp[t] sums dp[t − num] over every num.

Problem

Given an array of distinct positive integers nums and a target, return how many sequences of numbers from nums add up to target. Each number may be used any number of times, and sequences in a different order count as different (despite the name, these are permutations).

Constraints

Edge cases to test

Follow-up questions

What if negative numbers are allowed?
Infinitely many sequences could sum to the target, so you must cap the length; then the state becomes (target, length).
How does it differ from Coin Change II?
Order matters here, so the amount is the outer loop and every number is tried as the last one.

Solution

Java

public int combinationSum4(int[] nums, int target) {
    int[] dp = new int[target + 1];
    dp[0] = 1;
    for (int t = 1; t <= target; t++) {
        for (int num : nums) {
            if (num <= t) dp[t] += dp[t - num];
        }
    }
    return dp[target];
}

Python

def combination_sum4(nums, target):
    dp = [0] * (target + 1)
    dp[0] = 1
    for t in range(1, target + 1):
        for num in nums:
            if num <= t:
                dp[t] += dp[t - num]
    return dp[target]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int combinationSum4(vector<int> &nums, int target) {
        vector<int> dp = vector<int>(target + 1);
        dp[0] = 1;
        for (int t = 1; t <= target; t++) {
            for (int num : nums) {
                if (num <= t)
                    dp[t] += dp[t - num];
            }
        }
        return dp[target];
    }
};

More Dynamic Programming problems