jiazhongchen

subsets template

Nov 10th, 2020
793
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. 模板1, dfs 不带循环
  2.  
  3. class Solution {
  4. public:
  5.     /**
  6.      * @param nums: A set of numbers
  7.      * @return: A list of lists
  8.      */
  9.     vector<vector<int>> subsets(vector<int> &nums) {
  10.         vector<vector<int>> ans;
  11.         vector<int> path;
  12.         sort(nums.begin(), nums.end());
  13.         dfs(ans, path, 0, nums);
  14.         return ans;
  15.     }
  16.     void dfs(vector<vector<int>>& ans, vector<int>& path, int index, vector<int>& nums) {
  17.         if (index == nums.size()) {
  18.             ans.push_back(path);
  19.             return;
  20.         }
  21.         path.push_back(nums[index]);
  22.         dfs(ans, path, index+1, nums);
  23.         path.pop_back();
  24.         dfs(ans, path, index+1, nums);
  25.     }
  26. };
  27.  
  28. 模板2, dfs 带循环
  29.  
  30. class Solution {
  31. public:
  32.     /**
  33.      * @param nums: A set of numbers
  34.      * @return: A list of lists
  35.      */
  36.     vector<vector<int>> subsets(vector<int> &nums) {
  37.         vector<vector<int>> ans;
  38.         vector<int> path;
  39.         sort(nums.begin(), nums.end());
  40.         dfs(ans, path, 0, nums);
  41.         return ans;
  42.     }
  43.     void dfs(vector<vector<int>>& ans, vector<int>& path, int index, vector<int>& nums) {
  44.         ans.push_back(path);
  45.         for (int i = index; i < nums.size(); ++i) {
  46.             path.push_back(nums[i]);
  47.             dfs(ans, path, i+1, nums);
  48.             path.pop_back();
  49.         }
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment