This approach uses recursion and backtracking to generate all possible combinations by exploring each candidate. If a candidate is chosen, we explore further with the remaining target reduced by the candidate's value. We use backtracking to remove a candidate and try the next one. This way, we explore all possible combinations using depth-first search.
Time Complexity: O(2^T), where T is the target, as it potentially explores every combination of the candidates.
Space Complexity: O(T) for the recursion call stack and the path being explored.
1const combinationSum = function(candidates, target) {
2 const result = [];
3
4 function backtrack(remaining, path, start) {
5 if (remaining < 0) return;
6 if (remaining === 0) result.push([...path]);
7
8 for (let i = start; i < candidates.length; i++) {
9 path.push(candidates[i]);
10 backtrack(remaining - candidates[i], path, i);
11 path.pop();
12 }
13 }
14
15 backtrack(target, [], 0);
16 return result;
17};
18
19const candidates = [2, 3, 6, 7];
20const target = 7;
21console.log(combinationSum(candidates, target));
22
The JavaScript solution uses the backtracking approach. It explores combinations by recursively trying candidate numbers and keeping track with path
, reducing the target until zero, indicating a valid result.
We can use a dynamic programming (DP) approach to solve the Combination Sum problem. We maintain a DP array where each index represents the number of ways to form that particular sum using the candidates. The approach involves iterating through candidates and updating the DP array for each possible sum that can be formed with that candidate.
Time Complexity: Roughly O(T * N), for target T and candidates N.
Space Complexity: O(T) for the dp array itself in context of storage.
1using System;
2using System.Collections.Generic;
3
4class CombinationSumDPSolution {
5 public IList<IList<int>> CombinationSum(int[] candidates, int target) {
6 List<IList<int>>[] dp = new List<IList<int>>[target + 1];
7 dp[0] = new List<IList<int>> { new List<int>() };
8
9 for (int i = 1; i <= target; i++) {
10 dp[i] = new List<IList<int>>();
11 foreach (int candidate in candidates) {
12 if (i >= candidate) {
13 foreach (var combination in dp[i - candidate]) {
14 var newComb = new List<int>(combination);
15 newComb.Add(candidate);
16 dp[i].Add(newComb);
17 }
18 }
19 }
20 }
21 return dp[target];
22 }
23
24 static void Main(string[] args) {
25 int[] candidates = {2, 3, 6, 7};
26 int target = 7;
27 CombinationSumDPSolution solution = new CombinationSumDPSolution();
28 var result = solution.CombinationSum(candidates, target);
29 foreach (var combination in result) {
30 Console.WriteLine("[" + string.Join(", ", combination) + "]");
31 }
32 }
33}
34
In C#, the DP approach initializes arrays at indices corresponding to all sums up to target using candidates progressively, storing all valid combinations for each sum index after iterating through possible sums.