본문 바로가기

코딩 테스트/LeetCode

Medium - Combinations

728x90

 

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

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

 

Combinations - LeetCode

Can you solve this real interview question? Combinations - 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.   Example 1: Input: n = 4, k = 2 Output: [[1,2],[1,3

leetcode.com

문제 설명

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.

Constraints:

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

예시

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
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.
Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

풀이

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def recurse(cur: List[int], depth_to_go: int) -> List[List[int]]:
            if depth_to_go == 0:
                return [cur, ]
            
            ret = []
            left_boundary = 1
            right_boundary = n

            if len(cur) != 0:
                left_boundary = cur[-1] + 1

            for i in range(left_boundary, right_boundary + 1):
                recurse_ret = recurse(cur + [i], depth_to_go - 1)
                ret.extend(recurse_ret)

            return ret
        
        return recurse([], k)

 

 

728x90