Fork me on GitHub

[leetcode-78-Subsets]

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],
[]
]

思路:

回溯法。不是很懂=。= 学的的别人写的。貌似都是这个模板。。

    void dfs(vector<vector<int>>& result, vector<int>& temp, vector<int>& nums, int index)
    {
        result.push_back(temp);
        for (int i = index; i < nums.size();i++)
        {
            temp.push_back(nums[i]);//
            dfs(result,temp,nums,i+1);
            temp.erase(temp.end()-1);
        }
    }
    vector<vector<int>> subsets(vector<int>& nums)
    {
        vector<vector<int>>result;
        vector<int>temp;
        sort(nums.begin(), nums.end());//为什么要加上排序??
        dfs(result,temp,nums,0);
        return result;
    }

参考:

http://blog.csdn.net/happyaaaaaaaaaaa/article/details/51604217

https://discuss.leetcode.com/topic/19110/c-recursive-iterative-bit-manipulation-solutions-with-explanations

posted @ 2017-03-07 17:24  hellowOOOrld  阅读(148)  评论(0编辑  收藏  举报