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, 采用递归
2, 每层递归中,采用循环, 循环开始值,逐层递增。 如第一层,从1开始,第2层从第2开始。
3. 当生成一个组合时。 并以这个组合作样本,复制一份,在此基础上,生成下一个组合。
class Solution { public: vector<vector<int> > combine(int n, int k) { vector<vector<int> > ans(1); helper(ans, 1, n, k); ans.pop_back(); return ans; } void helper(vector<vector<int> > &ans, int start, int n, int k) { if (!k) return ans.push_back(ans.back()); for (int i=start; i<=n; i++) { ans.back().push_back(i); helper(ans, i+1, n, k-1); ans.back().pop_back(); } } };
原文地址:http://blog.csdn.net/elton_xiao/article/details/45025177