Cindy's Blog

アマゾンで働いているエンジニアの日常

LeetCode 78 Subsets

Select and not game

//select or not game!
//if nums.length = n
//then you have 2n options
//[1,2,3] => 23 = 8 sets

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        //select or not select game!
        //if nums.length = n
        //then you have 2^n options
        //[1,2,3] => 2^3 = 8 sets
        
        int size = nums.length;
        List<List<Integer>> answer = new ArrayList<>();
        List<Integer> current = new ArrayList<>();
        findSubsets(nums, size, 0, current, answer);
        
        return answer;
    }
    
    private void findSubsets(int[] nums, int size, int index, List<Integer> current, List<List<Integer>> answer){
        
        if (index == size){
            answer.add(new ArrayList<>(current));//deep copy
            return;
        }
        
        //not select
        findSubsets(nums, size, index + 1, current, answer);

        current.add(nums[index]);
        findSubsets(nums, size, index + 1, current, answer);
        //backtrack
        current.remove(current.size() - 1);
    }
}