题目描述(Medium)
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
题目链接
https://leetcode.com/problems/combinations/description/
Example 1:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
算法分析
方法一:dfs,类似【LeetCode】96. Permutations
提交代码(方法一):
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
vector<int> path;
dfs(path, 1, n, k, result);
return result;
}
void dfs(vector<int>& path, int step, int n, int k,
vector<vector<int>>& result) {
if (path.size() == k)
{
result.push_back(path);
return;
}
for (int i = step; i <= n; ++i)
{
path.push_back(i);
dfs(path, i + 1, n, k, result);
path.pop_back();
}
}
};