77. 组合

  1. class Solution {
  2. List<List<Integer>> result = new ArrayList();
  3. LinkedList<Integer> path = new LinkedList<>();
  4. public List<List<Integer>> combine(int n, int k) {
  5. backtracking(n,k,1);
  6. return result;
  7. }
  8. private void backtracking(int n, int k, int startIndex){
  9. //终止条件
  10. if (path.size() == k){
  11. result.add(new ArrayList<>(path));//收割结果进result
  12. return;//结束本层循环
  13. }
  14. //单层逻辑
  15. for (int i = startIndex; i <= n - (k - path.size()) + 1; i++){
  16. path.add(i);//收集
  17. backtracking(n,k,i+1);//递归
  18. path.removeLast();//回溯
  19. }
  20. }
  21. }

216. 组合总和 III

https://www.programmercarl.com/0216.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CIII.html#剪枝

class Solution {
    private:
    vector<vector<int>> result; // 存放结果集
    vector<int> path; // 符合条件的结果
    // targetSum:目标和,也就是题目中的n。
    // k:题目中要求k个数的集合。
    // sum:已经收集的元素的总和,也就是path里元素的总和。
    // startIndex:下一层for循环搜索的起始位置。
    void backtracking(int targetSum, int k, int sum, int startIndex) {
        if (path.size() == k) {
            if (sum == targetSum) result.push_back(path);
            return; // 如果path.size() == k 但sum != targetSum 直接返回
        }
        for (int i = startIndex; i <= 9; i++) {
            sum += i; // 处理
            path.push_back(i); // 处理
            backtracking(targetSum, k, sum, i + 1); // 注意i+1调整startIndex
            sum -= i; // 回溯
            path.pop_back(); // 回溯
        }
    }

    public:
    vector<vector<int>> combinationSum3(int k, int n) {
        result.clear(); // 可以不加
        path.clear();   // 可以不加
        backtracking(n, k, 0, 1);
        return result;
    }
};
class Solution {
private:
    vector<vector<int>> result; // 存放结果集
    vector<int> path; // 符合条件的结果
    void backtracking(int targetSum, int k, int sum, int startIndex) {
        if (sum > targetSum) { // 剪枝操作
            return; // 如果path.size() == k 但sum != targetSum 直接返回
        }
        if (path.size() == k) {
            if (sum == targetSum) result.push_back(path);
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) { // 剪枝
            sum += i; // 处理
            path.push_back(i); // 处理
            backtracking(targetSum, k, sum, i + 1); // 注意i+1调整startIndex
            sum -= i; // 回溯
            path.pop_back(); // 回溯
        }
    }

public:
    vector<vector<int>> combinationSum3(int k, int n) {
        result.clear(); // 可以不加
        path.clear();   // 可以不加
        backtracking(n, k, 0, 1);
        return result;
    }
};
public class Num_216 {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path =  new LinkedList<>();
    private void backTracking(int k ,int sum , int startIndex,int targetSum){
        if (path.size() == k){
            if (targetSum == sum){
                result.add(new ArrayList<>(path));
                return;
            }
        }
        //单层逻辑
        for (int i = startIndex; i <=9 ; i++) {
            sum += i;//操作
            path.add(i);//操作
            backTracking(k,sum,i+1,targetSum);//递归
            sum -= i;//回溯
            path.removeLast();//回溯

        }
    }
    public List<List<Integer>> combinationSum3(int k, int n) {
        backTracking(k,0,1,n);
        return result;
    }
}

17. 电话号码的字母组合

https://www.programmercarl.com/0017.%E7%94%B5%E8%AF%9D%E5%8F%B7%E7%A0%81%E7%9A%84%E5%AD%97%E6%AF%8D%E7%BB%84%E5%90%88.html#c-%E4%BB%A3%E7%A0%81

注意这个index可不是 77.组合(opens new window)216.组合总和III(opens new window)中的startIndex了。这个index是记录遍历第几个数字了,就是用来遍历digits的(题目中给出数字字符串),同时index也表示树的深度。

注意这里for循环,可不像是在回溯算法:求组合问题!(opens new window)回溯算法:求组合总和!(opens new window)中从startIndex开始遍历的
因为本题每一个数字代表的是不同集合,也就是求不同集合之间的组合,而77. 组合(opens new window)216.组合总和III(opens new window)都是是求同一个集合中的组合!

public class Num_17 {
    List<String > result = new ArrayList<>();//记录结果
    StringBuilder path = new StringBuilder();//记录路径
    private void backTracking(String digits,int index){
        String[] letterMap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};//数字和字母的映射表
        if (digits.length() == path.length()){//终止条件
            result.add(path.toString());
            return;
        }
        //单层
        int digit = digits.charAt(index) - '0';//将数字映射为字母
        String letters = letterMap[digit];
        for (int i = 0; i < letters.length(); i++) {

            path.append(letters.charAt(i));//操作
            //result.add(path.toString());
            backTracking(digits,index+1);//递归
            path.deleteCharAt(path.length()-1);//回溯
        }

    }
    public List<String> letterCombinations(String digits) {
        if (digits.length() == 0) return result;

        backTracking(digits,0);
        return result;
    }
}

39. 组合总和

https://www.programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html#java

本题和之前的77.组合(opens new window)216.组合总和III(opens new window)有两点不同:

  • 组合没有数量要求
  • 元素可无限重复选取

class Solution {
    List<List<Integer>> result = new ArrayList<>();//结果集
    LinkedList<Integer> path = new LinkedList<>();
    private void backTracking(int[] candidates, int targetSum,int sum,int startIndex){
        //结束条件
        if (sum > targetSum) return;
        if (targetSum == sum){
            result.add(new ArrayList<>(path));
            return;//结束本层循环
        }
        //单层逻辑
        for (int i = startIndex; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum += candidates[i];
            backTracking(candidates,targetSum,sum,i);// 关键点:不用i+1了,表示可以重复读取当前的数
            path.removeLast();
            sum -= candidates[i];
        }

    }
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTracking(candidates,target,0,0);
        return result;
    }
}

优化 求和后排序

// 剪枝优化
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates); // 先进行排序
        backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
        return res;
    }

    public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
        // 找到了数字和为 target 的组合
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = idx; i < candidates.length; i++) {
            // 如果 sum + candidates[i] > target 就终止遍历
            if (sum + candidates[i] > target) break;
            path.add(candidates[i]);
            backtracking(res, path, candidates, target, sum + candidates[i], i);
            path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
        }
    }
}

40. 组合总和 II

image.png

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    private void backingTracking(int[] candidates, int target, int sum, int startIndex) {
        if (target == sum) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length&& candidates[i] + sum <= target; i++) {
            if (i > startIndex && candidates[i] == candidates[i - 1] ) {
                continue;
            }
            //used[i] = true;
            path.add(candidates[i]);
            sum += candidates[i];
            backingTracking(candidates, target, sum, i + 1);
            //used[i] = false;
            path.remove(path.size() - 1);
            sum -= candidates[i];
        }
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //排序
        Arrays.sort(candidates);
        //boolean[] used = new boolean[candidates.length];
        backingTracking(candidates, target, 0, 0);
        return result;
    }
}
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    private void backingTracking(int[] candidates, int target, int sum, int startIndex) {
        if (target == sum) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length&& candidates[i] + sum <= target; i++) {
            if (i > startIndex && candidates[i] == candidates[i - 1] ) {
                continue;
            }
            //used[i] = true;
            path.add(candidates[i]);
            sum += candidates[i];
            backingTracking(candidates, target, sum, i + 1);
            //used[i] = false;
            path.remove(path.size() - 1);
            sum -= candidates[i];
        }
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //排序
        Arrays.sort(candidates);
        //boolean[] used = new boolean[candidates.length];
        backingTracking(candidates, target, 0, 0);
        return result;
    }
}

131. 分割回文串

image.png

class Solution {
    List<List<String>> result = new ArrayList<>();
    List<String> path = new ArrayList<>();

    private void backTracking(String s,int startIndex){
        //终止条件
        // 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了
        if (startIndex >= s.length()){
            result.add(new ArrayList<>(path));
            return;
        }
        //单层逻辑
        for (int i = startIndex; i < s.length(); i++) {
            //判断是否是回文
            if (isPalindrome(s,startIndex,i)){//如果是回文
                // 获取[startIndex,i]在s中的子串
                String substring = s.substring(startIndex, i + 1);
                path.add(substring);
            }else {
                continue;//不是回文跳过本层循环
            }
            backTracking(s,i+1);//递归 寻找i+1为起始位置的子串
            path.remove(path.size()-1);//回溯
        }
    }

    private boolean isPalindrome(String s, int start, int end) {
        for (int i =start ,j = end;i<j;i++,j--){
            if (s.charAt(i) != s.charAt(j)){
                return false;
            }
        }
        return true;
    }

    public List<List<String>> partition(String s) {
        backTracking(s,0);
        return result;
    }
}

93. 复原 IP 地址(分割)

image.png

class Solution {
    List<String> result = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        if (s.length() > 12) return result; // 算是剪枝了
        backTrack(s, 0, 0);
        return result;
    }

    // startIndex: 搜索的起始位置, pointNum:添加逗点的数量
    private void backTrack(String s, int startIndex, int pointNum) {
        if (pointNum == 3) {// 逗点数量为3时,分隔结束
            // 判断第四段⼦字符串是否合法,如果合法就放进result中
            if (isValid(s,startIndex,s.length()-1)) {
                result.add(s);
            }
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            if (isValid(s, startIndex, i)) {
                s = s.substring(0, i + 1) + "." + s.substring(i + 1);    //在str的后⾯插⼊⼀个逗点
                pointNum++;
                backTrack(s, i + 2, pointNum);// 插⼊逗点之后下⼀个⼦串的起始位置为i+2
                pointNum--;// 回溯
                s = s.substring(0, i + 1) + s.substring(i + 2);// 回溯删掉逗点
            } else {
                break;
            }
        }
    }

    // 判断字符串s在左闭⼜闭区间[start, end]所组成的数字是否合法
    private Boolean isValid(String s, int start, int end) {
        if (start > end) {
            return false;
        }
        if (s.charAt(start) == '0' && start != end) { // 0开头的数字不合法
            return false;
        }
        int num = 0;
        for (int i = start; i <= end; i++) {
            if (s.charAt(i) > '9' || s.charAt(i) < '0') { // 遇到⾮数字字符不合法
                return false;
            }
            num = num * 10 + (s.charAt(i) - '0');
            if (num > 255) { // 如果⼤于255了不合法
                return false;
            }
        }
        return true;
    }
}

//方法二:比上面的方法时间复杂度低,更好地剪枝,优化时间复杂度
class Solution {
    List<String> result = new ArrayList<String>();
    StringBuilder stringBuilder = new StringBuilder();

    public List<String> restoreIpAddresses(String s) {
        restoreIpAddressesHandler(s, 0, 0);
        return result;
    }

    // number表示stringbuilder中ip段的数量
    public void restoreIpAddressesHandler(String s, int start, int number) {
        // 如果start等于s的长度并且ip段的数量是4,则加入结果集,并返回
        if (start == s.length() && number == 4) {
            result.add(stringBuilder.toString());
            return;
        }
        // 如果start等于s的长度但是ip段的数量不为4,或者ip段的数量为4但是start小于s的长度,则直接返回
        if (start == s.length() || number == 4) {
            return;
        }
        // 剪枝:ip段的长度最大是3,并且ip段处于[0,255]
        for (int i = start; i < s.length() && i - start < 3 && Integer.parseInt(s.substring(start, i + 1)) >= 0
                && Integer.parseInt(s.substring(start, i + 1)) <= 255; i++) {
            // 如果ip段的长度大于1,并且第一位为0的话,continue
            if (i + 1 - start > 1 && s.charAt(start) - '0' == 0) {
                continue;
            }
            stringBuilder.append(s.substring(start, i + 1));
            // 当stringBuilder里的网段数量小于3时,才会加点;如果等于3,说明已经有3段了,最后一段不需要再加点
            if (number < 3) {
                stringBuilder.append(".");
            }
            number++;
            restoreIpAddressesHandler(s, i + 1, number);
            number--;
            // 删除当前stringBuilder最后一个网段,注意考虑点的数量的问题
            stringBuilder.delete(start + number, i + number + 2);
        }
    }
}