Sunday, November 22, 2015

[leetcode] Subsets

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> subsets(int[] nums) {
        if (nums == null || nums.length == 0) return result;
        Arrays.sort(nums);
        rec(new ArrayList<Integer>(), 0, nums);
        return result;
    }
    
    private void rec(List<Integer> fromUpper, int index, int[]nums){
        if (index == nums.length){
            result.add(new ArrayList<Integer>(fromUpper));
            return;
        }
        fromUpper.add(nums[index]);
        rec(fromUpper, index+1, nums);
        fromUpper.remove(fromUpper.size()-1);
        rec(fromUpper, index+1, nums);
    }
}

No comments:

Post a Comment