标签:
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], ]
Subscribe to see which companies asked this question
分析:
回溯法的典型
class Solution {
public:
void dfs(vector<vector<int > > &ans, vector<int> &subans, int start, int n, int k)
{
if (subans.size() == k)//已经获得答案,并且回溯
{
ans.push_back(subans);
return ;//回溯
}
for (int i = start; i <= n; i++)
{
subans.push_back(i);
dfs(ans, subans, i + 1, n, k);
subans.pop_back(); // 回溯去掉末尾元素
}
}
vector<vector<int> > combine(int n, int k) {
vector<vector<int > > result;
if (n < k || k == 0)
return result;
vector<int> subres;
dfs(result, subres, 1, n, k);
return result;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50835803
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895
<LeetCode OJ> 77. Combinations
标签:
原文地址:http://blog.csdn.net/ebowtang/article/details/50835803