Java straight forward iteration method, easy to understand.


  • 4
    Z

    Basic thought is that for every value in nums, generate new list based on result list with adding value to the result list, and add new list to the result list.

    public class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> list = new ArrayList<List<Integer>>();
            Arrays.sort(nums);
    
            for(int value : nums) { // for every value in nums, check the list, 
                if(list.isEmpty()) {
                    list.add(new ArrayList(Arrays.asList(value)));
                } else {
                    int size = list.size();
                    for(int i = 0; i < size; i++) {
                        List<Integer> temp = new ArrayList<>(list.get(i)); // based on exist list
                        temp.add(value); // add value to each list
                        list.add(temp);
                    }
                    list.add(new ArrayList(Arrays.asList(value))); // add current single value
                }
            }
            
            list.add(new ArrayList<Integer>());
            return list;
        }
    }

  • 9
    R

    Great solution! Can be more clean.

    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        ans.add(new ArrayList<>());
        Arrays.sort(nums);
    
        for (int num : nums)
        {
            int size = ans.size();
            for (int i = 0; i < size; i++)
            {
                List<Integer> tmp = new ArrayList<>(ans.get(i));
                tmp.add(num);
                ans.add(tmp);
            }
        }
        
        return ans;
    }

Log in to reply
 

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