Skip to content

Commit ae9740d

Browse files
committed
Combination Sum
1 parent 605bad8 commit ae9740d

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Backtracking/39-Combination-Sum.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
''' Leetcode- https://leetcode.com/problems/combination-sum/'''
2+
'''
3+
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.
4+
5+
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.
6+
7+
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
8+
9+
Example 1:
10+
11+
Input: candidates = [2,3,6,7], target = 7
12+
Output: [[2,2,3],[7]]
13+
Explanation:
14+
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
15+
7 is a candidate, and 7 = 7.
16+
These are the only two combinations.
17+
'''
18+
19+
20+
def combinationSum(candidates, target):
21+
res = []
22+
23+
def dfs(i, cur, total):
24+
if total == target:
25+
res.append(cur.copy())
26+
return
27+
if i >= len(candidates) or total > target:
28+
return
29+
30+
cur.append(candidates[i])
31+
dfs(i, cur, total+candidates[i])
32+
cur.pop()
33+
dfs(i+1, cur, total)
34+
35+
dfs(0, [], 0)
36+
return res
37+
38+
#T: O(2^T)
39+
#S: O(N)

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1313
- [x] [Permutations](Backtracking/46-Permutations.py)
1414
- [x] [Permutations II](Backtracking/47-Permutations-II.py)
1515
- [x] [Combinations](Backtracking/77-Combinations.py)
16+
- [x] [Combination Sum](Backtracking/39-Combination-Sum.py)
1617

0 commit comments

Comments
 (0)