관리 메뉴

솜씨좋은장씨

[leetCode] 216. Combination Sum III (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 216. Combination Sum III (Python)

솜씨좋은장씨 2020. 10. 23. 23:38
728x90
반응형

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

 

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Explanation:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.

Example 3:

Input: k = 4, n = 1
Output: []
Explanation: There are no valid combinations. [1,2,1] is not valid because 1 is used twice.

Example 4:

Input: k = 3, n = 2
Output: []
Explanation: There are no valid combinations.

Example 5:

Input: k = 9, n = 45
Output: [[1,2,3,4,5,6,7,8,9]]
Explanation:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
There are no other valid combinations.

Constraints:

  • 2 <= k <= 9
  • 1 <= n <= 60

첫번째 시도 - 시간초과

from itertools import combinations

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        range_list = list(range(1, n-k+1))
        
        k_comb = list(combinations(range_list, k))
        
        answer = [list(k_list) for k_list in k_comb if sum(list(k_list)) == n]
        
        return answer

사용하는 숫자의 범위가 1-9 사이인 것을 제대로 읽지 않아 시간초과가 발생하였습니다.

해당 내용을 반영한 코드는 아래의 내용입니다.

 

두번째 시도 - Solution

from itertools import combinations

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        num = n
        
        if num > 9:
            num = 9
        
        range_list = list(range(1, num+1))
        
        k_comb = list(combinations(range_list, k))
        
        answer = [list(k_list) for k_list in k_comb if sum(list(k_list)) == n]
        
        return answer

 

SOMJANG/CODINGTEST_PRACTICE

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

github.com

Comments