728x90
https://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
입력값이 [1,2,3]일 때 그림과 같은 간단한 트리를 구성한다면 이를 DFS하여 원하는 결과를 출력 할 수 있다.
def dfs(index, path):
...
for in range(index, len(nums)):
dfs(i + 1, path + [nums[i]])
경로 path를 만들어 나가면서 인덱스를 1씩 증가하는 형태로 깊이 탐색을 한다. 별도의 종료 조건 없이 탐색이 끝나면 저절로함수가 종료되게 한다.
from typing import List
def subsets(nums: List[int]) -> List[List[int]]:
result = []
def dfs(index, path):
# 매번 결과 추가
result.append(path)
# 경로를 만들면서 DFS
for i in range(index, len(nums)):
dfs(i + 1, path + [nums[i]])
dfs(0, [])
return result
728x90
'알고리즘 > 파이썬' 카테고리의 다른 글
[파이썬 알고리즘] 이진트리 기초 개념(1) (0) | 2022.05.23 |
---|---|
[파이썬 알고리즘] 백준-9095- 1,2,3 더하기 (0) | 2022.05.21 |
[파이썬 알고리즘] 그래프(DFS, BFS) 개념 (0) | 2022.05.20 |
[파이썬 알고리즘] 리트코드200 - 섬의개수(Number of Islands) (0) | 2022.05.19 |
[파이썬 알고리즘] 프로그래머스 - 기능 개발 (0) | 2022.05.19 |