Combinations
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], ]
递推点:加入i后,下一个加入的元素需要遍历i+1~n
因此可以基于k做递归。
base case: k=1,把所有的元素都逐个加入集合。
class Solution { public: vector<vector<int> > combine(int n, int k) { vector<vector<int> > result; vector<int> cur; Helper(result, cur, 1, n, k); return result; } void Helper(vector<vector<int> >& result, vector<int> cur, int begin, int n, int k) { if(k == 1) { for(int i = begin; i <= n; i ++) { cur.push_back(i); result.push_back(cur); cur.pop_back(); } } else { for(int i = begin; i <= n; i ++) { cur.push_back(i); Helper(result, cur, i+1, n, k-1); cur.pop_back(); } } } };
时间: 2024-10-15 14:21:59