Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find the target sum from the given array by backtracking using C#?
The target sum problem involves finding all possible combinations from a given array where the sum of elements equals a specific target value. The backtracking approach systematically explores all possible combinations by adding elements to the current solution and removing them when they don't lead to a valid result.
Given an array of positive integers and a target sum, we need to find all combinations where elements can be reused and their sum equals the target. For example, with array [1, 2, 3] and target 4, valid combinations are [1,1,1,1], [1,1,2], [1,3], and [2,2].
How Backtracking Works
The backtracking algorithm follows these steps −
Start with an empty combination and sum of 0
For each element in the array, add it to the current combination
If the sum equals target, save the combination
If the sum exceeds target, backtrack (remove the element and try next)
Continue until all possibilities are explored
Example
Here's a complete implementation using backtracking to find all combinations that sum to the target −
using System;
using System.Collections.Generic;
public class BackTracking {
public void FindCombinationSum(int[] array, int target) {
List<int> currentList = new List<int>();
List<List<int>> results = new List<List<int>>();
CombinationSum(array, target, currentList, results, 0, 0);
Console.WriteLine("All combinations that sum to " + target + ":");
foreach (var combination in results) {
Console.WriteLine("[" + string.Join(",", combination) + "]");
}
}
private void CombinationSum(int[] array, int target, List<int> currentList,
List<List<int>> results, int currentSum, int startIndex) {
if (currentSum == target) {
results.Add(new List<int>(currentList));
return;
}
if (currentSum > target) {
return;
}
for (int i = startIndex; i < array.Length; i++) {
currentList.Add(array[i]);
CombinationSum(array, target, currentList, results,
currentSum + array[i], i);
currentList.RemoveAt(currentList.Count - 1);
}
}
}
class Program {
static void Main(string[] args) {
BackTracking bt = new BackTracking();
int[] nums = { 1, 2, 3 };
bt.FindCombinationSum(nums, 4);
}
}
The output of the above code is −
All combinations that sum to 4: [1,1,1,1] [1,1,2] [1,3] [2,2]
Finding Unique Combinations Only
If you want to find combinations without reusing the same element, modify the recursive call −
using System;
using System.Collections.Generic;
public class UniqueBackTracking {
public void FindUniqueCombinations(int[] array, int target) {
List<int> currentList = new List<int>();
List<List<int>> results = new List<List<int>>();
Array.Sort(array);
CombinationSumUnique(array, target, currentList, results, 0, 0);
Console.WriteLine("Unique combinations that sum to " + target + ":");
foreach (var combination in results) {
Console.WriteLine("[" + string.Join(",", combination) + "]");
}
}
private void CombinationSumUnique(int[] array, int target, List<int> currentList,
List<List<int>> results, int currentSum, int startIndex) {
if (currentSum == target) {
results.Add(new List<int>(currentList));
return;
}
if (currentSum > target) {
return;
}
for (int i = startIndex; i < array.Length; i++) {
currentList.Add(array[i]);
CombinationSumUnique(array, target, currentList, results,
currentSum + array[i], i + 1);
currentList.RemoveAt(currentList.Count - 1);
}
}
}
class Program {
static void Main(string[] args) {
UniqueBackTracking bt = new UniqueBackTracking();
int[] nums = { 1, 2, 3, 4 };
bt.FindUniqueCombinations(nums, 5);
}
}
The output of the above code is −
Unique combinations that sum to 5: [1,4] [2,3]
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time Complexity | O(2^n) | In worst case, explores all possible subsets |
| Space Complexity | O(target/min) | Maximum depth of recursion is target divided by minimum element |
Conclusion
Backtracking provides an efficient approach to solve the target sum problem by systematically exploring all possible combinations while pruning invalid paths early. The algorithm can be easily modified to handle variations like finding unique combinations or limiting element reuse.
