标签:面试 leetcode algorithm 组合 递归
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], ]
组合问题,老思路---递归加循环,这个是组合里面比较简单的。
class Solution { public: vector<vector<int> > combine(int n, int k) { vector<vector<int> > ret; helper(k, 1, n, vector<int>(), ret); return ret; } void helper(int k, int start, int n, vector<int> part, vector<vector<int> > &ret){ if(k==part.size()){ ret.push_back(part); return; } for(int i=start; i<=n; ++i){ part.push_back(i); helper(k, i+1, n, part, ret); part.pop_back(); } } };
[LeetCode] Combinations [38],布布扣,bubuko.com
标签:面试 leetcode algorithm 组合 递归
原文地址:http://blog.csdn.net/swagle/article/details/30761165