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
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
def subsets(nums):
def dfs(index, path):
if len(path) == len(nums):
result.append(path[:])
return
if 1 <= len(path) < len(nums):
result.append(path[:])
for i in range(index, len(nums)):
dfs(i + 1, path + [nums[i]])
if nums == [0]:
return [[], [0]]
result = [[]]
dfs(0, [])
return result
nums = [1, 2, 3]
print(subsets(nums))
|
cs |
맞는 풀이: 백트래킹이 필요 없는 문제였다
1
2
3
4
5
6
7
8
9
10
11
12
|
def subsets(nums):
def dfs(index, path):
result.append(path[:])
for i in range(index, len(nums)):
dfs(i + 1, path + [nums[i]])
result = []
dfs(0, [])
return result
nums = [1, 2, 3]
print(subsets(nums))
|
cs |
result = [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
list가 추가된 순서로 작동과정을 파악할 수 있다.
for 문의 i는 초과된 인덱스를 접근할 수 없다. index가 len(nums)를 초과하면 for문 자체를 진입하기 않기 때문이다. 그래서 index에러를 따로 처리하지 않았다.
'알고리즘 문제풀이 with 파이썬 > LeetCode' 카테고리의 다른 글
[다익스트라] Network Delay Time (0) | 2021.10.06 |
---|---|
[DFS] Reconstruct Itinerary (0) | 2021.09.26 |
[DFS, 백트래킹] Combination Sum (0) | 2021.09.24 |
[DFS, 백트래킹] Letter Combinations of a Phone Number (0) | 2021.09.19 |
[DFS, 백트래킹] Number of Islands (0) | 2021.09.19 |