1 class Solution { 2 public: //递归 第一个位置分别为从1-n,对于每个值,后面的k-1个数再从后面的数里选剩下的k-1个数(子递归),等到第一个位置取到n-k的时候,剩下的k-1个正好是一种答案。 3 vector<vector<int>> combine(int n, int k) { 4 if(k==0 || n==0) 5 { 6 return {}; 7 } 8 vector<int> temp(k,0);//初始化记得不然下标访问不到 9 vector<vector<int>> res; 10 int count=0; 11 int start=1; 12 DFS(res,temp,count,start,n,k); 13 return res; 14 } 15 void DFS(vector<vector<int>>& res,vector<int>& temp,int& count,int start,int end,int k) 16 { 17 if(count==k) 18 { 19 res.push_back(temp); 20 return; 21 } 22 for(int i=start;i<=end;i++) 23 { 24 temp[count++]=i; 25 DFS(res,temp,count,i+1,end,k); 26 count--; 27 } 28 } 29 };