Combination Sum - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
def combinationSum(candidates, target):
def dfs(tot, index, path):
if tot == target:
result.append(path[:])
return
if tot > target:
return
for i in range(index, len(candidates)):
# print(f'dfs({tot + candidates[i]}, {i}, {path + [candidates[i]]})')
dfs(tot + candidates[i], i, path + [candidates[i]])
result = []
dfs(0, 0, [])
return result
|
cs |

dfs 문제는 풀기 전 항상 그림을 그려서 구조를 파악하자. 이 문제에 경우 2 3 5 7을 계속 가지 형태로 그려보면 도움이 된다. 자식 노드로의 이동은 dfs를 통해 발생하고, retrun을 만나면 for문을 통해 동일한 레벨의 노드를 탐색한다.
dfs(index +, path +)처럼 파라미터로 값을 넘기면 dfs가 리턴됐을 원상복귀가 되어있다. 파라미터로 값을 넘기자.
'알고리즘 문제풀이 with 파이썬 > LeetCode' 카테고리의 다른 글
[DFS] Reconstruct Itinerary (0) | 2021.09.26 |
---|---|
[DFS] Subsets (0) | 2021.09.25 |
[DFS, 백트래킹] Letter Combinations of a Phone Number (0) | 2021.09.19 |
[DFS, 백트래킹] Number of Islands (0) | 2021.09.19 |
[해시] Top K Frequent Elements (0) | 2021.09.18 |