Code Caprice Algorithm Training Camp Day 25 | 216. Combination Sum III, 17. Letter Combinations of Phone Numbers

Table of contents

216. Combined sums III

17. Alphabet combinations for phone numbers


216. Combined sums III

If you understand the combination problem, this question will be easier.

Topic link/article explanation: code caprice

Video explanation: How is it different from combination problems? How does the backtracking algorithm prune? | LeetCode: 216. Combined Sum III_哔哩哔哩_bilibili

Solution ideas:

This question is similar to Question 77, mainly because you are familiar with the template writing method of the backtracking algorithm, and then there are two pruning situations in this question, which can reduce the search time. The specific pruning operation is as follows (detailed notes in the code): Paper-cutting operation
1 : If the sum of the added elements is greater than the sum of the target, return in time to end this recursion and proceed to the next recursive operation;
pruning operation 2, when the control needs to reach k numbers, it needs to traverse to where to end at most , the specific operation is 9 - (k - path.size()) + 1 ! ! !

class Solution {
    LinkedList<Integer> path = new LinkedList<>();
    List<List<Integer>> result = new ArrayList<>();
    int sum = 0;

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

    public void backtracking(int k, int n, int startIndex){
        if(sum > n) return ; //剪纸操作一:如果添加的元素和大于目标之和时,及时return结束本次递归,进行下一次递归操作即可
        if(path.size() == k ){
            if(sum == n){
                result.add(new LinkedList(path));
                return;
            }
        }
        for(int i = startIndex; i <= 9 - (k - path.size()) + 1; i++ ){ //9 - (k - path.size()) + 1:这里是剪枝操作二,控制要达到k个个数时,最多还需要遍历到哪里结束即可
            path.add(i); //往path路径中及时添加元素
            sum += i; //添加的元素及时相加操作
            backtracking(k, n, i + 1); //不断的朝着深度方向进行搜索,直到遇到return结束方法的语句才算完成一次递归,紧接着进行回溯操作
            path.removeLast(); //递归遇到return后及时减去刚添加的元素,回溯到第一次递归的状态
            sum -= i; //递归遇到return后及时减去刚添加的元素,回溯到前一次递归的状态
        }
    }
}

17. Alphabet combinations for phone numbers

This question will be a bit difficult for everyone to do at the beginning. First, think for 20 minutes by yourself. If you have no idea, just look at the solution.

Topic link/article explanation: code caprice

Video explanation: You have to use the backtracking algorithm! | LeetCode: 17. Letter combinations of phone numbers_哔哩哔哩_bilibili

Solution ideas:

This question still has to be guided by Ka Ge, otherwise it will not be so easy to think of such a comprehensive solution, mainly the first step: first map the numeric keyboard into a string through the array subscript, and then take the letter combination in the string, Then draw the corresponding tree structure for step-by-step analysis, because the first time I wrote this question, I didn’t know where to start. When I saw the question, I was directly confused. I found out the relationship inside according to the tree-shaped solution. just fine.

class Solution {
    String[] mapLetter = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; //第一步:先把数字键盘通过数组下标映射成字符串,然后取字符串里面的字母组合
    LinkedList<String> path = new LinkedList<>();
    List<String> result = new ArrayList<>();
    StringBuilder temp = new StringBuilder(); //大量的字符串拼接可以选择更为高效的StringBuilder

    public List<String> letterCombinations(String digits) {
        if(digits == null || digits.length() == 0) return result; //这个剪枝操作是真恶心,还是需要直接判断如果digits == [""]或者不存在时时,直接return结果集即可
        bancktracking(digits,0);
        return result;
    }

    public void bancktracking(String digits, int index){ //index变量指向的是给定的数字字符串中的下标索引值,由于结果集中的大小和数字字符串大小一致,所以可以用过索引值控制回溯算法的终止条件,如下所示
        if(index == digits.length()){ //index从0开始索引给定的数字字符,通过index的索引值控制递归的终止条件,只有当满足终止条件时,才进行结果的处理
            result.add(temp.toString());
            return;
        }
        
        String letter = mapLetter[digits.charAt(index) - '0']; //digits[index]:获取给定数字字符串指定索引值的数字字符,从0开始获取的;digits[index] - '0':获取对应数字字符的int的数,传入到映射数组中,再获取数字字符对应的字符串!!!
        //这里要注意踩坑,一定是digits[index] - '0':表示两个字符串进行相加操作,得到的是int类型结果,'2'- '0' == 2,而不是digits[index] - 0:表示吧'2'先转换成ASCII码,其数值为50,再与0进行相减操作;
        for(int i = 0; i < letter.length(); i++){
            temp.append(letter.charAt(i));
            bancktracking(digits, index + 1);
            temp.deleteCharAt(temp.length() - 1);
        }
    }
}

Guess you like

Origin blog.csdn.net/tore007/article/details/130671627