Java Clean Code - Recursion


  • 1
    C
    public class Solution {
     	public List<List<Integer>> subsets(int[] nums) {
        	List<List<Integer>> subsets = new ArrayList<>();
    		List<Integer> template = new ArrayList<>();
    		subsets.add(template);
    		collectSubsets(nums, 0, template, subsets);
    		return subsets;
        }
    
    	private void collectSubsets(int[] nums, int start, List<Integer> template,
      			List<List<Integer>> subsets) {
    		if (start >= nums.length) {
    			return;
    		}
    
    		for (int i = start; i < nums.length; i++) {
    			List<Integer> subset = new ArrayList<>(template);
    			subset.add(nums[i]);
    			Collections.sort(subset);
    			subsets.add(subset);
    			collectSubsets(nums, i + 1, subset, subsets);
    		}
    	}
    }

Log in to reply
 

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