Java recursive solution


  • 0
    J
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> result = new ArrayList<>();
            Arrays.sort(nums);
            sets(nums, 0, new ArrayList<Integer>(), result);
            return result;
        }
        
        private void sets(int[] nums, int start, ArrayList<Integer> path, List<List<Integer>> result) {
            if (start >= nums.length) {
                List<Integer> res = new ArrayList<>();
                res.addAll(path);
                result.add(res);
                return;
            }
            int cnt = 0;
            int curNum = nums[start];
            for (int i = start; i < nums.length; i++) {
                if (nums[i] == curNum) cnt++;
            }
            // without current number
            sets(nums, start + cnt, path, result);
            for (int i = 0; i < cnt; i++) {
                path.add(curNum);
                sets(nums, start + cnt, path, result);
            }
            for (int i = 0; i < cnt; i++) path.remove(path.size() - 1);
        }
    

Log in to reply
 

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