1464 · The K-th Combination
Algorithms
Hard
Description
Solution
Notes
Discuss
Leaderboard
Description
There are n individuals whose numbers are 1,2,3,...,n, n are even numbers. Selecting half of them have C(n, n/2) combinations. Each combination is sorted by number from small to large, and then the sorted combination is sorted in lexicographic order. Please find the k-th combination.
- 1 \leq n \leq 20, 1 \leq k \leq C(n, n/2)1≤n≤20,1≤k≤C(n,n/2)
Example
Example 1:
Input: n=2, k=1
Output: [1]
Explanation:
All sorted combinations: [1],[2]
Example 2:
Input: n=4, k=2
Output: [1,3]
Explanation:
All sorted combinations: [1,2],[1,3],[1,4],[2,3],[2,4],[3,4]
解法1:DFS。subset的变种。
class Solution {
public:
/**
* @param n: The integer n
* @param k: The integer k
* @return: Return the combination
*/
vector<int> getCombination(int n, int k) {
vector<int> vol;
helper(n, k, 1, vol);
return res;
}
private:
vector<int> res;
int cnt = 0;
void helper(int n, int k, int pos, vector<int> &vol) {
if (!res.empty()) return;
if (vol.size() == (n >> 1)) {
cnt++;
if (cnt == k) {
res = vol;
}
return;
}
for (int i = pos; i <= n; i++) {
vol.push_back(i);
helper(n, k, i + 1, vol);
vol.pop_back();
}
return;
}
};
本文介绍如何通过DFS算法解决给定n个偶数,找到第k个由一半元素组成的组合问题。这些组合按数字顺序和字典序排序。解法涉及递归遍历和计数,适用于n<=20且1<=k<=C(n,n/2)的情况。

被折叠的 条评论
为什么被折叠?



