When comes to Subset II , How can I modify based on this code? (How to handle duplicates)


  • 0
    Y

    public class Solution {

    public List<List<Integer>> subsets(int[] num) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(num == null || num.length == 0) {
            return result;
        }
        Arrays.sort(num);
        ArrayList<Integer> list = new ArrayList<Integer>();
        util(result, list, num, 0);
    
        return result;
    }
    
    private void util(List<List<Integer>> result , ArrayList<Integer> list , int[] num , int pos){
        if(pos == num.length){
            result.add(new ArrayList<Integer>(list));
            return;
        }
        // do not add num[i]
        util(result , list , num , pos + 1);
    
        //add num[i]
        list.add(num[pos]);
        util(result , list , num , pos + 1);
        list.remove(list.size() - 1);
    }
    

    }


Log in to reply
 

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