My LeetCode Diary - Day26 BackTracking

39. Combination Sum

Link

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTracking(candidates, target, 0,0);
        return res;
    }

    void backTracking(int[] candidates, int target, int sum, int start) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        if (sum > target) {
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum += candidates[i];
            backTracking(candidates, target, sum,i);
            sum -= candidates[i];
            path.removeLast();
        }
    }
}

40. Combination Sum II

Link

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if (candidates.length == 0) {
            return res;
        }
        Arrays.sort(candidates);
        backTrack(candidates, target, 0,0);
        return res;
    }

    void backTrack(int[] candidates, int target, int sum, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        if (sum > target) {
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if ( i > index && candidates[i] == candidates[i - 1] ) {
        continue;
      }
            path.add(candidates[i]);
            sum +=candidates[i];
            backTrack(candidates, target, sum, i+1);
            sum -= candidates[i];
            path.removeLast();
        }
    }
}

131. Palindrome Partitioning

Link

class Solution {
    List<List<String>> res = new ArrayList<>();
    LinkedList<String> path = new LinkedList<>();
    public List<List<String>> partition(String s) {
        backTrack(s,0);
        return res;
    }

    void backTrack(String s, int index) {
        if (index == s.length()) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = index; i < s.length();i++) {
            if (isPalindrome(s,index, i)) {
                 path.addLast(s.substring(index, i + 1));
            } else {
                continue;
            }
            backTrack(s,i+1);
            path.removeLast();
        }
    }

    boolean isPalindrome(String s, int l, int r) {
        while (l <= r) {
            if (s.charAt(l) != s.charAt(r)) {
                return false;
            }
            l++;
            r--;
        }
        return true;
    }
}