Java Backtracking Solution


  • 0
    R
    public class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> result = new LinkedList<List<Integer>>();
            if(nums == null || nums.length==0) return result;
            Arrays.sort(nums);
            helper(nums,result,new LinkedList<Integer>(),0);
            result.add(new LinkedList<Integer>());//add empty set
            return result;
            
        }
        public void helper(int[] nums, List<List<Integer>> result, List<Integer> subset, int start){
            if(start>=nums.length) return;
            int prev = nums[start];
            for(int i = start; i < nums.length; i++){
                int cur = nums[i];
                if(start==i||cur!=prev){
                    List<Integer> newSet = new LinkedList<Integer>(subset);
                    newSet.add(cur);
                    result.add(newSet);
                    helper(nums,result,newSet,i+1);
                    prev = cur;
                }
            }
        }
    }
    

Log in to reply
 

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