leetcode — subsets

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

/**
 * Source : https://oj.leetcode.com/problems/subsets/
 *
 *
 * Given a set of distinct integers, S, return all possible subsets.
 *
 * Note:
 *
 * Elements in a subset must be in non-descending order.
 * The solution set must not contain duplicate subsets.
 *
 * For example,
 * If S = [1,2,3], a solution is:
 *
 * [
 *   [3],
 *   [1],
 *   [2],
 *   [1,2,3],
 *   [1,3],
 *   [2,3],
 *   [1,2],
 *   []
 * ]
 */
public class SubSet {
    private List<List<Integer>> result = new ArrayList<List<Integer>>();

    /**
     *
     *
     * @return
     */
    public List<List<Integer>> subset (int[] arr) {
        List<Integer> set = new ArrayList<Integer>();
        Arrays.sort(arr);
        recursion(arr, 0, set);
        return result;
    }

    private void recursion (int[] arr, int index, List<Integer> set) {
        if (index == arr.length) {
            return;
        }
        for (int i = index; i < arr.length; i++) {
//            if (i < arr.length - 1 && arr[i] == arr[i+1]) {
//                continue;
//            }
            set.add(arr[i]);
            List<Integer> temp = new ArrayList<Integer>(set);
            result.add(temp);
            recursion(arr, i + 1, set);
            set.remove(set.size()-1);
        }
    }

    private static void print (List<List<Integer>> list) {
        for (List<Integer> arr : list) {
            System.out.println(Arrays.toString(arr.toArray(new Integer[arr.size()])));
        }
        System.out.println();
    }

    public static void main(String[] args) {
        SubSet subSet = new SubSet();
        int[] arr = new int[]{1,2,3};
        print(subSet.subset(arr));

    }
}
posted @ 2017-10-27 00:14  lacker  阅读(117)  评论(0编辑  收藏  举报