您的位置:首页 > 其它

[LeetCode] Combinations

2015-06-16 23:45 375 查看
A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts:

What is a partial solution and when is it finished? --- In this problem, the partial solution is a combination (sol). It is finished once it contains k elements.

How to find all the partial solutions? --- In the following code, I simply traverse all the possible starting elements (start).

When to make recursive calls? --- In the following code, once an element is added to the partial solution, we call the function to generate the remaining elements recursively.

Of course, remember to recover to the previous status once a partial solution is done. In the following code, line 18 (sol.pop_back()) is for this purpose.

The following should be self-explanatory :)

class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int> > res;
vector<int> sol;
combination(1, n, k, sol, res);
return res;
}
private:
void combination(int start, int n, int k, vector<int>& sol, vector<vector<int> >& res) {
if (k == 0) {
res.push_back(sol);
return;
}
for (int i = start; i <= n; i++) {
sol.push_back(i);
combination(i + 1, n, k - 1, sol, res);
sol.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: