관리 메뉴

솜씨좋은장씨

[leetCode] 77. Combinations (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 77. Combinations (Python)

솜씨좋은장씨 2020. 11. 18. 21:02
728x90
반응형

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

You may return the answer in any order.

 

Example 1:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Example 2:

Input: n = 1, k = 1
Output: [[1]]

 

Constraints:

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

Solution

from itertools import combinations

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        range_list = list(range(1, n+1))
        
        comb_list = list(combinations(range_list, k))
        
        return comb_list

Solution 해설

먼저 인자로 받은 n을 기준으로 1 ~ n 범위의 숫자를 가지는 리스트를 만들어줍니다.

그 다음 itertools의 combinations를 활용하여 인자로 받은 k 개의 원소를 갖는 combinaion리스트를 만들어주면 끝!

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments