package medium;

import java.util.ArrayList;
import java.util.List;

import utils.CommonUtils;

public class Subsets {

    public static void main(String...strings){
        int[] nums = new int[]{1,2,3};
        List<List<Integer>> result = subsets(nums);
        CommonUtils.printIntegerList(result);
    }
    
    public static List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList();
        List<Integer> empty = new ArrayList();
        result.add(empty);
        if(nums == null) return result;
        for(int i = 0; i < nums.length; i++){
            List<List<Integer>> temp = new ArrayList();//you'll have to create a new one here, otherwise, it'll throw ConcurrentModificationException.
            for(List<Integer> list : result){
                List<Integer> newList = new ArrayList(list);
                newList.add(nums[i]);
                temp.add(newList);
            }
            result.addAll(temp);
        }
        return result;
    }

}

@@ -160,16 +160,18 @@
 rings)%7B%0A
+//
         
@@ -201,16 +201,55 @@
 1,2,3%7D;%0A
+        int%5B%5D nums = new int%5B%5D%7B1,2,2%7D;%0A
         
@@ -284,16 +284,29 @@
  subsets
+_backtracking
 (nums);%0A
@@ -1053,11 +1053,963 @@
 ;%0A    %7D%0A
+    %0A    /**this post: https://discuss.leetcode.com/topic/46159/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning%0A     * is really cool!*/%0A    public static List%3CList%3CInteger%3E%3E subsets_backtracking(int%5B%5D nums) %7B%0A        List%3CList%3CInteger%3E%3E result = new ArrayList();%0A        backtracking(result, new ArrayList%3C%3E(), nums, 0);%0A        return result;%0A    %7D%0A%0A    private static void backtracking(List%3CList%3CInteger%3E%3E result, List%3CInteger%3E temp, int%5B%5D nums, int start) %7B%0A        //ATTN: you'll have to make a new list here before entering the for loop%0A        result.add(new ArrayList(temp));%0A        for(int i = start; i %3C nums.length; i++)%7B%0A            if(i != start && nums%5Bi%5D == nums%5Bi-1%5D) continue;//add this line here to skip duplicates for Subsets II%0A            temp.add(nums%5Bi%5D);%0A            backtracking(result, temp, nums, i+1);%0A            temp.remove(temp.size()-1);%0A        %7D%0A    %7D
 %0A%7D%0A

use backtracking to solve Subsets I & II