回溯Leetcode 77 Combinations
阿新 • • 發佈:2018-12-28
Leetcode 77
Combinations
- Problem Description:
經典回溯問題:給出n個數字,要求返回其中k個數的組合情況。
具體的題目資訊:
https://leetcode.com/problems/combinations/description/ - Example:
- Solution:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int >> res;
vector<int> t;
combination(1, k, n, t, res);
return res;
}
void combination(int i, int k, int n, vector<int>& t, vector<vector<int>>& res) {
if (k == t.size()) {
res.push_back(t);
return;
} else {
for (int j = i; j <= n; j++) {
t.push_back(j);
combination(j+1, k, n, t, res);
t.erase(t.begin()+t.size()-1);
}
}
}
};