m1ndy5's coding blog

LeetCode 77. Combinations(조합) with Python 본문

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

LeetCode 77. Combinations(조합) with Python

정민됴 2024. 1. 10. 10:07

https://leetcode.com/problems/combinations/

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        answer = []

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

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

        dfs([], 1, n, k)

        return answer

라이브러리 사용해서 간편하게 나타내기

import itertools

def combine(self, n, k):
    return list(itertools.combinations(range(1, n+1), k))

이 또한 itertools 모듈을 사용하면 좀 더 편하고 성능좋게 나타낼 수 있다.