Java solution, recursion, easy-understand


  • 1
    A
    public class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> lists = new LinkedList<List<Integer>>();
            List<Integer> list = new LinkedList<Integer>();
            if(nums.length == 0){
                return lists;
            }
            Arrays.sort(nums);
            lists.add(list);
            subsets(nums, lists, 0);
            return lists;
        }
        
        static void subsets(int[]nums, List<List<Integer>> lists, int start){
            if(start >= nums.length){
                return;
            }
            List<List<Integer>> nlists = new LinkedList<List<Integer>>(lists);
            for(int i = 0; i < nlists.size(); i++){
                List<Integer> l = new LinkedList<Integer>(nlists.get(i));
                l.add(nums[start]);
                if(!lists.contains(l)){
                    lists.add(l);
                }
            }
            subsets(nums, lists, start + 1);
            return;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.