77. Combinations
题目
分析:求给定数字n,k的组合数,方法是采用深度搜索算法,代码如下(copy网上代码)
1 class Solution { 2 public: 3 void dfs77(vector<vector<int > > &ans, vector<int> subans, int start, int n, int k) 4 { 5 if (subans.size() == k) 6 { 7 ans.push_back(subans); return ; 8 } 9 for (int i = start; i <= n; i++) 10 { 11 subans.push_back(i); 12 dfs77(ans, subans, i + 1, n, k); 13 subans.pop_back(); // 满足一个条件或者该分支递归完后要删除最后一个 14 } 15 } 16 vector<vector<int> > combine(int n, int k) { 17 vector<vector<int > > ans; 18 if (n < k || k == 0) return ans; 19 vector<int> subans; 20 dfs77(ans, subans, 1, n, k); 21 return ans; 22 } 23 };
--------------------------------------------------------------------------------分割线------------------------------------------------------------------
78. Subsets
题目
分析:求一个集合的所有子集,代码如下(copy网上代码)
1 class Solution { 2 public: 3 vector<vector<int>>res; 4 vector<int>ans; 5 vector<vector<int>> subsets(vector<int>& nums) { 6 if(nums.empty()) return res; 7 sort(nums.begin(), nums.end()); 8 dfs(0, ans, nums); 9 return res; 10 11 } 12 void dfs(int k, vector<int>ans, vector<int> nums){ 13 res.push_back(ans); 14 for(int i = k; i < nums.size(); i++){ 15 ans.push_back(nums[i]); 16 dfs(i + 1, ans, nums); 17 ans.pop_back(); 18 } 19 } 20 };
时间: 2024-10-27 04:18:56