Clean and concise solution backtracking


  • 1
    M
    public class Solution {
    public List<List<Integer>> combinationSum(int[] nums, int target) {
        LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();
        LinkedList<Integer> list = new LinkedList<Integer>();
        Arrays.sort(nums);
        combinationSum(nums, target, 0, 0, list, result);
        return result;
    }
    
    private void combinationSum(int[] nums, int target, int start, int sum, LinkedList<Integer> list, LinkedList<List<Integer>> result) {
        if(sum >= target) {
            if(sum == target) result.add(new LinkedList(list));
            return;
        }
        for(int k = start; k < nums.length; k++) {
            list.addLast(nums[k]);
            combinationSum(nums, target, k, sum+nums[k], list, result);
            list.removeLast();
        }
    }
    }

Log in to reply
 

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