Skip to content

Solution #39 - Neha Amin - 15/07/2025 #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions BackTracking/#39 - Combination Sum - Medium/Explanation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# 39. Combination Sum

**Difficulty:** *Medium*
**Category:** *Backtracking, Recursion*
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/combination-sum/)

---

## 📝 Introduction

*Given an array of distinct integers and a target, the task is to return all unique combinations where the chosen numbers sum up to the target. Each number in the array may be used an unlimited number of times.*

*Constraints typically include:<br>
- All input numbers are distinct positive integers.<br>
- Each number may be used any number of times in a combination.<br>
- Total number of unique combinations is less than 150.*

---

## 💡 Approach & Key Insights

*The core idea is to explore all valid combinations recursively using the "pick / not pick" technique:<br>
- At each step, either pick the current number and stay at the same index (since it can be reused), or skip it and move to the next index.<br>
- Maintain a running sum and a temporary combination list.<br>
- If the running sum becomes 0, we’ve found a valid combination and we save it.<br>
- Backtrack after each recursive call to try new combinations.*

---

## 🛠️ Breakdown of Approaches

### 1️⃣ Recursive Backtracking (Pick / Non-pick)

- **Explanation:** *We recursively explore all combinations starting from index 0. For each number, we can choose to either include it (and stay at the same index) or exclude it (move to next index). Whenever target becomes 0, we add the current path to the result.*
- **Time Complexity:** *O(2^t) – where t = target value. Actual complexity depends on pruning.*
- **Space Complexity:** *O(k * x) – where x is the number of valid combinations, k is average length.*
- **Example/Dry Run:**

```plaintext
Input: [2,3,6,7], target = 7
Sorted: [2,3,6,7]

Start at index 0:
- Pick 2 → [2], target = 5
- Pick 2 → [2,2], target = 3
- Pick 2 → [2,2,2], target = 1
- Pick 2 → [2,2,2,2], target = -1 (backtrack)
- Skip 2, pick 3 → [2,2,3], target = 0 → ✅
- Skip 2, pick 3 → [2,3], target = 2
- Pick 3 again → target = -1 (backtrack)
- Pick 7 → [7], target = 0 → ✅

Output: [[2,2,3], [7]]
```

---

## 📊 Complexity Analysis

| Approach | Time Complexity | Space Complexity |
| ------------------- | --------------- | ---------------- |
| Recursive Backtrack | O(2^t) | O(k × x) |

---

## 📉 Optimization Ideas

*Although the recursion tree explores all combinations, sorting the input and pruning branches where target < candidate[i] can improve efficiency. Additionally, memoization can be applied but is typically unnecessary within the constraint of <150 combinations.*

---

## 📌 Example Walkthroughs & Dry Runs

```plaintext
Example 1:
Input: [2,3,6,7], target = 7

Recursive Tree:
Start with []
Pick 2: [2] → target=5
Pick 2 again: [2,2] → target=3
Pick 2 again: [2,2,2] → target=1
Pick 2 again → exceeds → backtrack
Backtrack and pick 3 → [2,2,3] → ✅ target=0

Pick 7: [7] → ✅

Output: [[2,2,3],[7]]

Example 2:
Input: [2], target = 1

Only choice: 2 > 1 → cannot pick → return []

Output: []
```

---

## 🔗 Additional Resources

- [Backtracking explanation](https://medium.com/upsolve-digest/template-for-backtracking-problems-part1-the-basics-75f744cab925)
- [Python recursion guide](https://realpython.com/python-thinking-recursively/)

---

Author: Neha Amin <br>
Date: 19/07/2025
26 changes: 26 additions & 0 deletions BackTracking/#39 - Combination Sum - Medium/combinationSum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution {
public:
void findCombination(int ind, int target, vector<int>& arr, vector<vector<int>>& ans, vector<int>& ds) {
if (ind == arr.size()) {
if (target == 0) {
ans.push_back(ds);
}
return;
}
// Pick the element
if (arr[ind] <= target) {
ds.push_back(arr[ind]);
findCombination(ind, target - arr[ind], arr, ans, ds);
ds.pop_back();
}
// Do not pick the element
findCombination(ind + 1, target, arr, ans, ds);
}

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> ds;
findCombination(0, target, candidates, ans, ds);
return ans;
}
};
18 changes: 18 additions & 0 deletions BackTracking/#39 - Combination Sum - Medium/combinationSum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
ds = []

def findCombination(ind: int, target: int):
if ind == len(candidates):
if target == 0:
ans.append(ds[:])
return
if candidates[ind] <= target:
ds.append(candidates[ind])
findCombination(ind, target - candidates[ind])
ds.pop()
findCombination(ind + 1, target)

findCombination(0, target)
return ans