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], ]解法一:
recursion的思路。首先把几个base case列出来。然后从n开始到k,选一个数字i,然后考虑在省下的i-1个数中,选择k-1个数字的combination。
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; if(k==0) return res; if(k>=n){ vector<int> tmp; for(int i=1; i<=n; i++) tmp.push_back(i); res.push_back(tmp); return res; } else if(k==1){ for(int i=1; i<=n; i++){ vector<int> tmp; tmp.push_back(i); res.push_back(tmp); } return res; } else{ for(int i=n; i>=k; i--){ vector<vector<int>> tmp = combine(i-1, k-1); for(int j=0; j<tmp.size(); j++){ tmp[j].push_back(i); res.push_back(tmp[j]); } } } return res; } };