78.Subsets

思路:
  • dfs,每个元素有两种选择,选或者不选。
class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        sort(begin(nums),end(nums));
        vector<vector<int>> res;
        vector<int> tmp;
        dfs(nums,0,res,tmp);
        return res;
    }
    void dfs(vector<int>& nums,int i,vector<vector<int>>& res,vector<int>& tmp){
        if(i == nums.size()) {
            res.push_back(tmp);
            //tmp.clear();  //注意,因为下面有回溯的过程,所以tmp不用清空
            return ;
        }
        for(int j = 0; j < 2; j++){
            if(j == 0){
                dfs(nums,i+1,res,tmp);
            }else{
                tmp.push_back(nums[i]);
                dfs(nums,i+1,res,tmp);
                tmp.pop_back();
            }
        }
    }
};
posted @ 2017-06-14 09:34  UniMilky  阅读(129)  评论(0编辑  收藏  举报