Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ae9740d

Browse files
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

Lines changed: 39 additions & 0 deletions
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

Lines changed: 1 addition & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /