题目描述链接:https://leetcode-cn.com/problems/combinations/
解题思路:DFS进行深搜。
LeetCode C++参考代码如下:
class Solution { public: vector<vector<int>>res; bool vis[1005]; int count; vector<vector<int>> combine(int n, int k) { vector<int>ans; dfs(n,0,k,ans); return res; } void dfs(int n,int i,int k,vector<int>ans){ if(ans.size()==k){ res.push_back(ans); ans.pop_back(); return; } //可以考虑下将ans.push_back()、ans.pop_back()写在for循环的外部,和此题中写在for循环内部的区别 for(int j=i+1;j<=n;j++){ ans.push_back(j); dfs(n,j,k,ans); ans.pop_back(); } } };