Java, recusrion with explanation


  • 1
    D
    public class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) 
        {
            // sort, later use sorted feature to avoid duplicate subsets
           Arrays.sort(nums);
            
            List<List<Integer>> res = new ArrayList<>();
            // add '[] '
            res.add(new ArrayList<>());
            // call helper method
            helper(res, new ArrayList<Integer>(), nums, 0);
            
            return res;
        }
        
        private void helper(List<List<Integer>> res, List<Integer> colt, int[] nums, int start)
        {
            for (int i = start; i < nums.length; i++)
            {
                // avoid duplicate
                if (i > start && nums[i] == nums[i - 1]) { continue; }
                // add new element
                colt.add(nums[i]);
                
                res.add(new ArrayList<>(colt));
                helper(res, colt, nums, i + 1);
                
                // remove, set back
                colt.remove(colt.size() - 1);
            }
        }
        
    }
    

Log in to reply
 

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