题目:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [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>> res; deal(res, vector<int>(), 1, k, n); return res; } void deal(vector<vector<int>>& res, vector<int> temp, int start, int k, int n){ if(temp.size() == k){ res.push_back(temp); return; } for(int i = start; i <= n; i++){ temp.push_back(i); deal(res, temp, i+1, k, n); temp.pop_back(); } } };