Program to find number of distinct combinations that sum up to k in python

Suppose we have a list of distinct numbers called nums and another number k, we have to find the number of distinct combinations that sum up to k. You can reuse numbers when creating combinations.

So, if the input is like nums = [2, 4, 5] and k = 4, then the output will be 2, as we can make two such groups like [2, 2] and [4].

Algorithm

This problem uses dynamic programming approach. We create a table where table[i] represents the number of ways to sum up to i.

To solve this, we will follow these steps ?

  • Create a table of size k + 1 and fill with 0
  • Set table[0] = 1 (one way to make sum 0: use no numbers)
  • For each number in nums, update the table for all possible sums
  • For each sum from num to k, add table[i - num] to table[i]
  • Return table[k]

Example

def count_combinations(nums, k):
    # Create DP table
    table = [1] + [0] * k
    
    for num in nums:
        for i in range(num, k + 1):
            table[i] += table[i - num]
    
    return table[k]

# Test the function
nums = [2, 4, 5]
k = 4
result = count_combinations(nums, k)
print(f"Number of combinations that sum to {k}: {result}")
Number of combinations that sum to 4: 2

How It Works

Let's trace through the example step by step ?

def count_combinations_with_trace(nums, k):
    table = [1] + [0] * k
    print(f"Initial table: {table}")
    
    for num in nums:
        print(f"\nProcessing number: {num}")
        for i in range(num, k + 1):
            old_value = table[i]
            table[i] += table[i - num]
            if table[i] != old_value:
                print(f"  table[{i}] = {old_value} + table[{i - num}] = {table[i]}")
        print(f"Table after processing {num}: {table}")
    
    return table[k]

nums = [2, 4, 5]
k = 4
result = count_combinations_with_trace(nums, k)
print(f"\nFinal result: {result}")
Initial table: [1, 0, 0, 0, 0]

Processing number: 2
  table[2] = 0 + table[0] = 1
  table[3] = 0 + table[1] = 0
  table[4] = 0 + table[2] = 1
Table after processing 2: [1, 0, 1, 0, 1]

Processing number: 4
  table[4] = 1 + table[0] = 2
Table after processing 4: [1, 0, 1, 0, 2]

Processing number: 5
Table after processing 5: [1, 0, 1, 0, 2]

Final result: 2

Using Class-Based Solution

class Solution:
    def solve(self, nums, k):
        table = [1] + [0] * k
        
        for num in nums:
            for i in range(num, k + 1):
                table[i] += table[i - num]
        
        return table[k]

# Test the solution
ob = Solution()
nums = [2, 4, 5]
k = 4
print(ob.solve(nums, k))
2

Conclusion

This dynamic programming solution efficiently finds the number of combinations that sum to k with time complexity O(n×k) and space complexity O(k). The key insight is building up solutions for smaller sums to solve larger ones.

Updated on: 2026-03-25T12:43:26+05:30

467 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements