My Java Solution based on Subset I


  • 0
    B
    public class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            List<Integer> sublist = new ArrayList<Integer>();
            
            Arrays.sort(nums);
            
            for(int i = 0; i <= nums.length; i++){
                getSubsets(res, sublist, nums, i, 0);
            }
            
            return res;
        }
        private void getSubsets(List<List<Integer>> res, List<Integer> sublist, int[] nums, int k, int position){
            if(sublist.size() == k){
                res.add(new ArrayList<Integer>(sublist));
                return;
            }
            
            for(int i = position; i < nums.length;){
                sublist.add(nums[i]);
                getSubsets(res, sublist, nums, k, i+1);
                sublist.remove(sublist.size()-1);
                i++;
                while (i < nums.length && nums[i] == nums[i - 1]) {
                    i++;
                }
            }
            
            return;
        }
    }

Log in to reply
 

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