Java backtracking concise and easy to understand


  • 0
    S
    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;
            this.target = 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));
                return;
            }
            for(int i = start; i<candidates.length; i++) {
                thisList.add(candidates[i]);
                backtrack(thisList, currSum+candidates[i], i);
                thisList.remove(thisList.size()-1);
            }
        }
    }
    

    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.