Java backtracking concise and easy to understand

  • 0
    class Solution {
        List<List<Integer>> mainList;
        int[] candidates;
        int target;
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            this.mainList = new ArrayList<>();
            this.candidates = candidates;
   = target;
            backtrack(new ArrayList<>(), 0, 0);
            return mainList;
        private void backtrack(List<Integer> thisList, int currSum, int start) {
            if(currSum > target) return;
            if(currSum == target) {
                this.mainList.add(new ArrayList<>(thisList));
            for(int i = start; i<candidates.length; i++) {
                backtrack(thisList, currSum+candidates[i], i);

    No need to sort the input array or keep track of remaining elements.

Log in to reply

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