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 = [123]
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 = [123]
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에러를 따로 처리하지 않았다.

+ Recent posts