Short and Easy to understand Recursive JAVA solution


  • 3
    W
    public class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            combine(candidates, 0, target, res, new ArrayList<Integer>());
            return res;
        }
        private void combine(int[] nums, int start, int target, List<List<Integer>> res, List<Integer> path){
            if (target < 0) return;
            if (target == 0){
                res.add(path);
                return;
            }
            for (int i = start; i < nums.length; i++){
                if (i > start && nums[i] == nums[i - 1]) continue;
                List<Integer> currentPath = new ArrayList<Integer>(path);
                currentPath.add(nums[i]);
                combine(nums, i + 1, target - nums[i], res, currentPath);
            }
        }
    }

Log in to reply
 

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