[leetcode] 77. Combinations
2023. 2. 6. 09:53ㆍ노트/Algorithm : 알고리즘
77. Combinations
Companies
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],[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.
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.
Constraints:
- 1 <= n <= 20
- 1 <= k <= n
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
results = []
def dfs(elements, start, k):
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
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[leetcode] 78. Subsets (0) | 2023.02.08 |
---|---|
[leetcode] 39. Combination Sum (0) | 2023.02.08 |
[leetcode] 17. Letter Combinations of a Phone Number (1) | 2023.01.03 |
[leetcode] 200. Number of Islands (0) | 2023.01.02 |
[leetcode] 347. Top K Frequent Elements (0) | 2022.12.20 |