zoukankan      html  css  js  c++  java
  • 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));
    
        }
    }
    
  • 相关阅读:
    调试D2JS
    PG 中 JSON 字段的应用
    面试----
    机器学习面试题
    闭包和装饰器
    scss-混合@mixin @include @function
    scss基本使用及操作函数
    常用的scss函数(mixin)
    二叉搜索树基本操作实现
    判断一棵树是否是二叉搜索树
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7740489.html
Copyright © 2011-2022 走看看