问题:
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], ]
思路:backtrack。由于状态容易now是引用类型传入传出的,所以用完之后要恢复原样。
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > com;
if(n < k)
return com;
vector<int> now;
produce(com, now, n, k, 0, 1);
return com;
}
void produce(vector<vector<int> > &com, vector<int> &now, int n, int k, int count, int from)
{
if(count == k)
{
com.push_back(now);
return;
}
if(from > n)
return;
produce(com, now, n, k, count, from+1);
now.push_back(from);
produce(com, now, n, k, count+1, from+1);
now.pop_back(); //注意要将now改回原样
}
};

本文介绍了一个使用回溯法解决组合问题的算法,用于生成指定范围内的所有组合,具体步骤包括定义组合类、实现组合生成函数以及演示实例。
809

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



