Simple Java Recursive solution.


  • 0
    S
    public class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> result = new ArrayList();
            helper(result, 0, nums);
            return result;
        }
        
        private void helper(List<List<Integer>> result, int index, int[] nums) {
            if (index == nums.length) {
                result.add(new ArrayList());
                return;
            }
            int num = nums[index];
            index++;
            helper(result, index, nums);
            int prevSize = result.size();
            for (int i = 0; i < prevSize; i++) {
                List<Integer> currList = result.get(i);
                List<Integer> newList = new ArrayList(currList);
                newList.add(num);
                result.add(newList);
            }
        }
    }

Log in to reply
 

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