1. 程式人生 > >leetcode 78 Subsets

leetcode 78 Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

這道題和第77題一樣,第一感覺用dfs就可以求解,這種型別的題關鍵點是返回條件的確定,本題和77題一樣,當到達陣列的末端時,達到結束條件,程式碼記錄如下:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ret;
        vector<int> tmp;
        ret.push_back(tmp); //empty subsets
        dfsSubsets(ret, tmp, nums, 0);
        return ret;
    }

    void dfsSubsets(vector<vector<int>> &ret, vector<int> &tmp, const vector<int>& nums, int next)
    {
        if (next == nums.size())
            return;
        for (int i = next; i < nums.size(); i++)
        {
            tmp.push_back(nums[i]); 
            ret.push_back(tmp); //Attension!
            dfsSubsets(ret, tmp, nums, i + 1);
            tmp.pop_back();
        }
    }
};