C# || How To Get Array Combination Sum Equal To Target Value Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to get an array combination sum equal to a target value using C#.


1. Combination Sum – Problem Statement

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:


Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

Example 2:


Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3:


Input: candidates = [2], target = 1
Output: []

Example 4:


Input: candidates = [1], target = 1
Output: [[1]]

Example 5:


Input: candidates = [1], target = 2
Output: [[1,1]]


2. Combination Sum – Solution

The following is a solution which demonstrates how to get an array combination sum equal to a target value.

The main idea of this solution is to generate subsets of the different combinations that can be matched together, checking to see if any sum up to equal the target value.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


[[2,2,3],[7]]
[[2,2,2,2],[2,3,3],[3,5]]
[]
[[1]]
[[1,1]]

Was this article helpful?
👍 YesNo

Leave a Reply