Share my simple and fast recursion solution, Java.


  • 0
    G

    public class Solution {

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        return subsets(nums, nums.length - 1);
    }
    
    public List<List<Integer>> subsets(int[] nums, int bound){
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(nums == null || bound < 0){
            result.add(new ArrayList<Integer>());
            return result;
        }
        int difIndex = bound - 1;
        while(difIndex >= 0 && nums[difIndex] == nums[bound]){
            difIndex--;
        }
        List<List<Integer>> pre = subsets(nums, difIndex);
        for(int i = 0; i < pre.size(); i++){
            for(int count = 0; count < bound - difIndex; count++){
                List<Integer> temp = new ArrayList<Integer>(pre.get(i));
                for(int j = 0; j <= count; j++){
                    temp.add(nums[bound]);
                }
                result.add(temp);
            }
        }
        result.addAll(pre);
        return result;
    }
    

    }


Log in to reply
 

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