Skip to main content
Back to problems
#377
Medium Algorithms

Combination sum iv

Array Dynamic Programming
55.0% acceptance
Jan 12, 2026
7755
699
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. The test cases are generated so that the answer can fit in a 32-bit integer.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn combination_sum4(nums: Vec<i32>, target: i32) -> i32 {
    let target = target as usize;
    let mut dp = vec![0; target + 1];
    dp[0] = 1;
    
    for i in 1..=target {
      for &num in &nums {
        if num as usize <= i {
          dp[i] += dp[i - num as usize];
        }
      }
    }
    
    dp[target]
  }
}