LeetCode DFS Subsets

思路:

DFS,时间复杂度O(2^n),空间复杂度O(n)

DFS有两种路径可以选择:

method one是先选;method two是先往下走;


c++ code:

class Solution {
private:
    //Subsets : DFS
    void dfs(const vector<int> &nums, int depth, vector<int> &path, vector<vector<int>> &res) {
        if(depth == nums.size()) {
            res.push_back(path);
            return;
        }
        //method two
        /*
        //not select the element, go deep
        dfs(nums,depth+1,path,res);
        //select the element
        path.push_back(nums[depth]);
        dfs(nums,depth+1,path,res);
        path.pop_back();
        */
        //method one
        path.push_back(nums[depth]);
        dfs(nums,depth+1,path,res);
        path.pop_back();
        dfs(nums, depth+1, path, res);
    }
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        vector<int> path;
        dfs(nums,0,path,res);
        return res;
    }
};

java code:

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> path = new ArrayList<>();
        
        if(nums.length == 0) return res;
        
        Arrays.sort(nums);
        
        dfs(res, path, nums, 0);
        
        return res;
    }
    
    private void dfs(List<List<Integer>> res, List<Integer> path, int[] nums, int index) {
        res.add(new ArrayList<Integer>(path));
        
        for(int i = index; i < nums.length; ++i) {
            path.add(nums[i]);
            dfs(res, path, nums, i + 1);
            path.remove(path.size() - 1);
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值