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

class Solution:
    def __init__(self):
        self.res = []
    def subsets(self, nums: List[int]) -> List[List[int]]:      
        def backtracking(path,index):
            self.res.append(path.copy())
            for i in range(index,len(nums)):
                backtracking(path+[nums[i]],i+1)
        backtracking([],0)
        return self.res

 





class Solution {
public:
    vector<vector<int>> res;
    void backtrack(vector<int>& nums, vector<int>& path, int start) {
        res.push_back(path);
        for(int i = start; i < nums.size(); ++i) {
            path.push_back(nums[i]);
            backtrack(nums, path, i+1);
            path.pop_back();
        }
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<int> path = vector<int>();
        backtrack(nums,path,0);
        return res;
    }
};

 


 

posted @ 2018-04-20 17:03  乐乐章  阅读(522)  评论(0编辑  收藏  举报