-
描述
- 给定两个整数 n 和 k,
- 返回 1 ... n 中所有可能的 k 个数的组合。
-
示例:
- 输入: n = 4, k = 2
- 输出:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
-
实现
class Solution { public: void dfs(vector<vector<int>>& res, vector<int>& path, int start, int n, int k){ if(path.size()==k){ res.push_back(path); return; } for(int i=start; i<=n; i++){ path.push_back(i); dfs(res, path, i+1, n, k); path.pop_back(); } } vector<vector<int>> combine(int n, int k) { vector<vector<int>>res; vector<int>path; dfs(res, path, 1, n, k); return res; } };