LeetCode 77 - Combinations
题目描述
[MEDIUM]
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:
1 | Input: n = 4, k = 2 |
Example 2:
1 | Input: n = 1, k = 1 |
Example 3:
1 | Input: n = 2, k = 2 |
Constraints:
1 <= n <= 20
1 <= k <= n
思路
We can solve this using backtracking:
- We build combinations incrementally.
- When the current combination reaches size k, we add it to the result.
- For each step, we choose a number i from the current position up to n, and recursively explore.
different from permutation: no need to keep track of used, and start position already resolve the case of [1,2] and [2,1]
Think of this as exploring a decision tree:
- At each node, you choose the next number to include.
- Stop when you have selected k numbers.
- Backtrack (remove the last element) and try the next number.
代码
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.