m1ndy5's coding blog

LeetCode 78. Subsets with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 78. Subsets with Python

정민됴 2024. 1. 11. 09:00

https://leetcode.com/problems/subsets/

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        answers = []

        def dfs(pair, i, k, n):
            if len(pair) == k:
                answers.append(pair[:])
                return

            for j in range(i, n):
                pair.append(nums[j])
                dfs(pair, j+1, k, n)
                pair.pop()

        for i in range(n+1):
            dfs([], 0, i, n)

        return answers

부분집합의 길이가 0, 1, 2, 3, ... 일때 해당 부분집합을 다 찾을 수 있도록 풀었다.