반응형
250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 해시테이블 #heapq #파이썬 #리트코드 #알고리즘
- exoplayer #mediaplayer #엑소플레이어 #안드로이드 #android
- dfs #bfs #트리구조 #이진트리 #leetcode #python #파이썬
- 다익스트라 #dijkstra #leetcode #파이썬 #python #algorithm #787
- dfs #python #leetcode
- leetcode #subsets #dfs #itertools #python
- dfs #그래프 #graph #python #leetcode #course #schedule
- dfs #leetcode #python
- python #백준 #2580 #스도쿠 #dfs #백트래킹
- 리트코드 #팰린드롬 #파이썬
- Python #leetcode #dfs #그래프 #백트래킹
- 아스테리스크 #Asterisk #파이썬
- final #java #자바 #안드로이드
- 파이썬 #zip
- dfs #bfs #leetcode #python
- 2004 #조합 0의 개수 #백준
- 백준 #파이썬 #bfs #백트래킹 #1697 #숨바꼭질
- python #백준 #9375 #패션왕 #신해빈
- leetcode #python #dfs #재귀
- 다익스트라 #알고리즘 #bfs #그리디 #다이나믹프로그래밍 #leetcode #python
- context #android #getApplicationContext #activity #생명주기 #lifecycle
- dfs #bfs #이진트리 #파이썬 #리트코드
- handler #looper #thread #runnable #핸들러 #루퍼 #스레드 #러너블
- 코틀린 #Do it #깡샘 #안드로이드
- dfs #bfs #트리구조 #이진트리 #leetcode #파이썬 #python
- gcd #최대공약수 #백준 #2981 #검문
- dfs #python #leetcode #combination
- AsyncTask #doinbackground #스레드 #thread #android #안드로이드
- dfs #leetcode #python #graph #그래프
- dfs #이진트리 #트리구조 #직렬화 #역직렬화 #파이썬 #리트코드 #leetcode #python
Archives
- Today
- Total
멋진 개발자가 되고 싶다
[LeetCode/Python] 39. 조합의 합(Combination Sum) 본문
728x90
반응형
숫자 집합 candidates를 조합하여 합이 target이 되는 원소를 나열하라.
각 원소는 중복으로 나열 가능하다.
Example:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3], [7]]
1. 내가 직접 푼 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
output = []
def dfs(stack, hap):
if hap == target:
output.append(stack)
elif hap > target:
return
for candidate in candidates:
dfs(stack + [candidate], hap + candidate)
dfs([], 0)
outputs = []
for val in output:
a = sorted(val)
if a not in outputs:
outputs.append(a)
return outputs
|
cs |
해설:
재귀 함수로 dfs를 구현했다.
속도는 하위 5%로 엄청 허접하게 나왔다!
dfs 함수를 통해 합이 target 값이 나올 때까지 오지게 굴렸고
이렇게 되면 문제점이 뭐냐면
[2,2,3]과 [3,2,2], [2,3,2]가 모두 output에 들어간다.
겹치는 건 없애줘야 돼서 sort를 시켜서 비교를 통해 최종 출력 outputs를 리턴한다.
** 깔끔한 코드 **
2. DFS로 중복 조합 그래프 탐색
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def dfs(csum, index, path):
# 종료 조건
if csum < 0:
return
if csum == 0:
result.append(path)
return
# 자신 부터 하위 원소 까지의 나열 재귀 호출
for i in range(index, len(candidates)):
dfs(csum - candidates[i], i, path + [candidates[i]])
dfs(target, 0, [])
return result
|
cs |
해설:
내 생각에 이 코드가 1번 코드보다 속도 면에서 빨랐던 이유는 index라는 변수를 통해 접근해서 그런 것 같다.
나 같은 경우 슬라이싱을 통해 candidates를 잘라가며 처리했는데 그럴 경우 속도는 1번 코드와 별 차이가 없다.
728x90
반응형
'Algorithm Study > leetcode' 카테고리의 다른 글
[LeetCode/Python] 207. 코스 스케줄(Course Schedule) (0) | 2021.07.29 |
---|---|
[LeetCode/Python] 332. 일정 재구성(Reconstruct Itinerary) (0) | 2021.07.29 |
[LeetCode/Python] 77. 조합(Combinations) (0) | 2021.07.25 |
[LeetCode/Python] 1260. DFS와 BFS (0) | 2021.07.25 |
[LeetCode/Python] 17. Letter Combinations of a Phone Number (0) | 2021.07.24 |