题目链接:https://leetcode.com/problems/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], ]
思路:DFS + 回溯. 每到一个新的位置可以取当前的值, 也可以不取, 这样当我们拿够了k个数就可以加到结果集合中去. 如果当前的位置大于了最大值, 就可以退出了.
看样子leetcode又添加新数据了, 一个月之前的vec值传递是可以过掉的, 现在过不了了, 所以把值传递改为引用传递即可.
代码如下:
class Solution {
public:
void DFS(int n, int k, int cur, vector<int>& vec)
{
if(k ==0) return ans.push_back(vec);
if(cur > n) return;
DFS(n, k, cur+1, vec);
vec.push_back(cur);
DFS(n, k-1, cur+1, vec);
vec.pop_back();
}
vector<vector<int>> combine(int n, int k) {
if(n <1 || n < k) return {};
vector<int> vec;
DFS(n, k, 1, vec);
return ans;
}
private:
vector<vector<int>> ans;
};