Combinations.
Topic
Analysis: The combination number of the given number N,k, the method is to use the depth search algorithm, the code is as follows (copy online code)
1 classSolution {2 Public:3 voidDfs77 (vector<vector<int> > &ans, vector<int> Subans,intStartintNintk)4 {5 if(subans.size () = =k)6 {7Ans.push_back (Subans);return ;8 }9 for(inti = start; I <= N; i++)Ten { One Subans.push_back (i); ADfs77 (ans, subans, i +1, N, k); -Subans.pop_back ();//satisfy a condition or delete the last one after the branch has been recursively completed - } the } -vector<vector<int> > Combine (intNintk) { -vector<vector<int> >ans; - if(N < k | | k = =0)returnans; +vector<int>Subans; -Dfs77 (ans, Subans,1, N, k); + returnans; A } at};
--------------------------------------------------------------------------------Split Line-------------------------------------- ----------------------------
Subsets.
Topic
Analysis: Ask for all subsets of a collection, code as follows (copy online code)
1 classSolution {2 Public:3vector<vector<int>>Res;4vector<int>ans;5vector<vector<int>> Subsets (vector<int>&nums) {6 if(Nums.empty ())returnRes;7 sort (Nums.begin (), Nums.end ());8Dfs0, ans, nums);9 returnRes;Ten One } A voidDfsintK, vector<int>ans, vector<int>nums) { - res.push_back (ans); - for(inti = k; I < nums.size (); i++){ the Ans.push_back (Nums[i]); -DFS (i +1, ans, nums); - Ans.pop_back (); - } + } -};
Leetcode (25)