반응형
leetcode.com/problems/subsets/
Subsets - 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

부분집합을 만들어야 하는 문제에서,
permutation / combination 라이브러리는 모든 경우의 수를 iterate 형태로 반환하기 때문에 시간초과가 발생할 수 있었다.
부분집합을 dfs 방식으로 생성하는 기본 문제이자 코드.
아래 코드는 이 책을 참고해서 작성하였다.
![]() |
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def subsets(self, nums: List[int]) -> List[List[int]]: | |
# 트리 구조의 dfs로 해결하기 | |
result = [] | |
def dfs(idx, path): | |
result.append(path) | |
# idx 순서대로 경로를 만들면서 dfs 연산 | |
for next_idx in range(idx, len(nums)): | |
dfs(next_idx + 1, path + [nums[next_idx]]) | |
dfs(0, []) | |
return result | |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] LeetCode 56. merge intervals (0) | 2020.11.06 |
---|---|
[Python] LeetCode 743. Network Delay Time (0) | 2020.11.05 |
[Python] 프로그래머스. 예상 대진표 (Level 2) (0) | 2020.10.29 |
[Python] LeetCode 3. Longest Substring without repeating characters (0) | 2020.10.27 |
[Python] LeetCode 739. Daily Temperature (0) | 2020.10.24 |