您的位置:首页 > 编程语言 > C语言/C++

[LeetCode] Combinations

2015-07-29 17:15 405 查看
Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,

If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

解题思路:

这道题的题意是找到1-n的数字中找出k个数的所有组合。可以采用递归回溯法。比较简单。

class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
if(n < 0 || k < 0 || n < k){
return result;
}
vector<int> item;
combineHelper(n, k, item, result);

return result;
}

void combineHelper(int n, int k, vector<int> item, vector<vector<int>>& result){
int size = item.size();
if(size>=k){
result.push_back(item);
return;
}
int last = size==0 ? 0 : item[size - 1];
if(n - last + size < k){ //无法达到k的大小了
return;
}
for(int i = last + 1; i <= n; i++){
item.push_back(i);
combineHelper(n, k, item, result);
item.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode