78. Subsets(backtracking 套路)

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

解答:这道题不算难,还是套路,但是我的做法比较慢,别的人用位运算更快,不过我没仔细看别人怎么做的。应该注意,这道题里面的套路也就是backtracking的套路基本就是这道题的答案,可以记一下:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
          vector<vector<int>> result;
          vector<int> res;
          sub(nums,result,res,0,nums.size());
          return result;
    }
    void sub(vector<int>& nums,vector<vector<int>>& result, vector<int> res,int begin,int target)
    {
          result.push_back(res);
          for(int i=begin;i1,target);
              res.pop_back();
          }

    }


};

别人的位操作做法:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
          vector<vector<int>> result;
          vector<int> res;
          sub(nums,result,res,0,nums.size());
          return result;
    }
    void sub(vector<int>& nums,vector<vector<int>>& result, vector<int> res,int begin,int target)
    {
          result.push_back(res);
          for(int i=begin;i1,target);
              res.pop_back();
          }

    }


};

你可能感兴趣的:(leetcode算法心得)