_what

博客园 首页 新随笔 联系 订阅 管理
递归
//c++
class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int> > res;
        vector<int> v;
        sort(nums.begin(), nums.end());
        getSub(nums, 0, res, v);
        return res;
    }

    void getSub(vector<int>& nums, int d, vector<vector<int> >& res, vector<int>& v ) {
        res.push_back(v);
        for(int i = d; i < nums.size(); i++) {
            v.push_back(nums[i]);
            getSub(nums, i + 1, res, v);
            v.pop_back();
        }
    }
};




# python
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
         if not nums: return [[]]
         res = self.subsets(nums[1:])
         return res + [[nums[0]] + s for s in res]
posted on 2020-04-12 09:59  _what  阅读(188)  评论(0编辑  收藏  举报