Subsets

Subsets

Given a set of distinct integers, nums, return all possible subsets.code

Note: Elements in a subset must be in non-descending order. The
solution set must not contain duplicate subsets. For example, If nums
= [1,2,3], a solution is:rem

[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]io

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(nums);
        helper(result, list, nums, 0);
        return result;
    }
    private void helper(List<List<Integer>> result, List<Integer> list, int[] nums, int index) {
        result.add(new ArrayList<Integer>(list));

        for (int i = index; i < nums.length; i++) {
            if (list.contains(nums[i])) {
                continue;
            }
            list.add(nums[i]);
            helper(result,list,nums,i + 1);
            list.remove(list.size() - 1);
        }
    }
}
相關文章
相關標籤/搜索