Subsets

来源:互联网 发布:监控电脑屏幕的软件 编辑:程序博客网 时间:2024/05/17 21:41

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

可能是好久没看这道题了上来写了两个错误的解法。解法少了一些情况。

因为题目需要找到全部的subset,那么在每个dfs里边,除了要往cur 中间结果里边保存变量的同时,也要把当前的结果保存到最终的结果集里边。

代码:

 public List<List<Integer>> subsets(int[] nums) {        List<List<Integer>> result = new ArrayList<>();                if(nums == null || nums.length == 0) return result;                dfs(result, new ArrayList<Integer>(), 0, nums);        return result;    }        private void dfs(List<List<Integer>> result, List<Integer> cur, int curIndex, int[] nums){        if(curIndex == nums.length){            result.add(new ArrayList<Integer>(cur));            return;        }        result.add(new ArrayList<>(cur)); // this is important        for(int i=curIndex;i<nums.length;i++){            cur.add(nums[i]);            dfs(result, cur, i+1, nums);            cur.remove(cur.size()-1);        }    }


0 0
原创粉丝点击