less than 1 minute read

77. Combinations

문제 링크

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

문제 설명

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

제한 사항

  • 1 <= n <= 20
  • 1 <= k <= n

입출력 예 #1

  1. Input : n = 4, k = 2
  2. Output : [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
  3. Explanation : There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

입출력 예 #2

  1. Input : n = 1, k = 1
  2. Output : [[1]]
  3. Explanation : There is 1 choose 1 = 1 total combination.

문제 풀이

  1. dfs 기법을 이용한 수열 출력
  2. itertools 모듈의 combinations를 이용한 풀이
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        results = []

        def dfs(elements, start: int, k: int):
            if k == 0 :
                results.append(elements[:])
            
            for i in range(start, n + 1):
                elements.append(i)
                dfs(elements, i + 1, k - 1)
                elements.pop()
            
        dfs([], 1, k)
        return results
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        return list (itertools.combinations(range(1, n + 1), k))

Comments