Java Backtracking


  • 1
    T
    public class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> ans = new ArrayList<>();
            List<Integer> path = new ArrayList<>();
            ans.add(new ArrayList<>(path));
            if (nums == null || nums.length == 0) {
                return ans;
            }
            int start = 0;
            helper(ans, path, start, nums);
            
            return ans;
        }
        
        private void helper(List<List<Integer>> ans, List<Integer> path, int start, int[] nums) {
            if (start == nums.length) {
                return;
            }
            
            for (int i = start; i < nums.length; ++i) {
                path.add(nums[i]);
                ans.add(new ArrayList<>(path));
                helper(ans, path, i + 1, nums);
                path.remove(path.size() - 1);
            }
            
        }
    }

Log in to reply
 

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