Subsets

来源:互联网 发布:linux 打开vim编辑器 编辑:程序博客网 时间:2024/06/05 20:33
题目描述:

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

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

分析:递归计算
代码:
class Solution {    public List<List<Integer>> subsets(int[] nums) {        List<List<Integer>> result = subsetsHelper(nums, 0);        result.add(new ArrayList<Integer>());        return result;    }    private List<List<Integer>> subsetsHelper(int[] nums, int index) {        if (index == nums.length) {            return new ArrayList<>();        }        List<List<Integer>> result = new ArrayList<>();        List<List<Integer>> subresult = subsetsHelper(nums, index + 1);        for (List<Integer> l : subresult) {            result.add(new ArrayList<>(l));            l.add(nums[index]);        }        List<Integer> single = new ArrayList<>();        single.add(nums[index]);        subresult.add(single);        result.addAll(subresult);        return result;    }}


原创粉丝点击