Skip to content

Commit d7a478f

Browse files
committed
new commit
1 parent 67de492 commit d7a478f

File tree

4 files changed

+152
-0
lines changed

4 files changed

+152
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# 39. Combination Sum
2+
3+
**Difficulty:** *Medium*
4+
**Category:** *Backtracking, Recursion*
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/combination-sum/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
*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.*
12+
13+
*Constraints typically include:<br>
14+
- All input numbers are distinct positive integers.<br>
15+
- Each number may be used any number of times in a combination.<br>
16+
- Total number of unique combinations is less than 150.*
17+
18+
---
19+
20+
## 💡 Approach & Key Insights
21+
22+
*The core idea is to explore all valid combinations recursively using the "pick / not pick" technique:<br>
23+
- 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>
24+
- Maintain a running sum and a temporary combination list.<br>
25+
- If the running sum becomes 0, we’ve found a valid combination and we save it.<br>
26+
- Backtrack after each recursive call to try new combinations.*
27+
28+
---
29+
30+
## 🛠️ Breakdown of Approaches
31+
32+
### 1️⃣ Recursive Backtracking (Pick / Non-pick)
33+
34+
- **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.*
35+
- **Time Complexity:** *O(2^t) – where t = target value. Actual complexity depends on pruning.*
36+
- **Space Complexity:** *O(k * x) – where x is the number of valid combinations, k is average length.*
37+
- **Example/Dry Run:**
38+
39+
```plaintext
40+
Input: [2,3,6,7], target = 7
41+
Sorted: [2,3,6,7]
42+
43+
Start at index 0:
44+
- Pick 2 → [2], target = 5
45+
- Pick 2 → [2,2], target = 3
46+
- Pick 2 → [2,2,2], target = 1
47+
- Pick 2 → [2,2,2,2], target = -1 (backtrack)
48+
- Skip 2, pick 3 → [2,2,3], target = 0 → ✅
49+
- Skip 2, pick 3 → [2,3], target = 2
50+
- Pick 3 again → target = -1 (backtrack)
51+
- Pick 7 → [7], target = 0 → ✅
52+
53+
Output: [[2,2,3], [7]]
54+
```
55+
56+
---
57+
58+
## 📊 Complexity Analysis
59+
60+
| Approach | Time Complexity | Space Complexity |
61+
| ------------------- | --------------- | ---------------- |
62+
| Recursive Backtrack | O(2^t) | O(k × x) |
63+
64+
---
65+
66+
## 📉 Optimization Ideas
67+
68+
*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.*
69+
70+
---
71+
72+
## 📌 Example Walkthroughs & Dry Runs
73+
74+
```plaintext
75+
Example 1:
76+
Input: [2,3,6,7], target = 7
77+
78+
Recursive Tree:
79+
Start with []
80+
Pick 2: [2] → target=5
81+
Pick 2 again: [2,2] → target=3
82+
Pick 2 again: [2,2,2] → target=1
83+
Pick 2 again → exceeds → backtrack
84+
Backtrack and pick 3 → [2,2,3] → ✅ target=0
85+
86+
Pick 7: [7] → ✅
87+
88+
Output: [[2,2,3],[7]]
89+
90+
Example 2:
91+
Input: [2], target = 1
92+
93+
Only choice: 2 > 1 → cannot pick → return []
94+
95+
Output: []
96+
```
97+
98+
---
99+
100+
## 🔗 Additional Resources
101+
102+
- [Backtracking explanation](https://medium.com/upsolve-digest/template-for-backtracking-problems-part1-the-basics-75f744cab925)
103+
- [Python recursion guide](https://realpython.com/python-thinking-recursively/)
104+
105+
---
106+
107+
Author: Neha Amin <br>
108+
Date: 19/07/2025
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
void findCombination(int ind, int target, vector<int>& arr, vector<vector<int>>& ans, vector<int>& ds) {
4+
if (ind == arr.size()) {
5+
if (target == 0) {
6+
ans.push_back(ds);
7+
}
8+
return;
9+
}
10+
// Pick the element
11+
if (arr[ind] <= target) {
12+
ds.push_back(arr[ind]);
13+
findCombination(ind, target - arr[ind], arr, ans, ds);
14+
ds.pop_back();
15+
}
16+
// Do not pick the element
17+
findCombination(ind + 1, target, arr, ans, ds);
18+
}
19+
20+
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
21+
vector<vector<int>> ans;
22+
vector<int> ds;
23+
findCombination(0, target, candidates, ans, ds);
24+
return ans;
25+
}
26+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
3+
ans = []
4+
ds = []
5+
6+
def findCombination(ind: int, target: int):
7+
if ind == len(candidates):
8+
if target == 0:
9+
ans.append(ds[:])
10+
return
11+
if candidates[ind] <= target:
12+
ds.append(candidates[ind])
13+
findCombination(ind, target - candidates[ind])
14+
ds.pop()
15+
findCombination(ind + 1, target)
16+
17+
findCombination(0, target)
18+
return ans

0 commit comments

Comments
 (0)