Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- Git
- github
- 자연어처리
- Docker
- 코로나19
- hackerrank
- Kaggle
- 캐치카페
- 백준
- ubuntu
- leetcode
- 금융문자분석경진대회
- 편스토랑 우승상품
- 프로그래머스 파이썬
- 파이썬
- Baekjoon
- AI 경진대회
- SW Expert Academy
- ChatGPT
- 더현대서울 맛집
- gs25
- PYTHON
- 프로그래머스
- Real or Not? NLP with Disaster Tweets
- 편스토랑
- dacon
- 데이콘
- 우분투
- programmers
- 맥북
Archives
- Today
- Total
솜씨좋은장씨
[leetCode] 216. Combination Sum III (Python) 본문
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
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
[leetCode] 179. Largest Number (Python) (0) | 2020.10.25 |
---|---|
[leetCode] 27. Remove Element (Python) (0) | 2020.10.24 |
[leetCode] 206. Reverse Linked List (Python) (0) | 2020.10.22 |
[leetCode] 1078. Occurrences After Bigram (Python) (0) | 2020.10.21 |
[leetCode] 451. Sort Characters By Frequency (Python) (0) | 2020.10.20 |
Comments