当前位置:   article > 正文

算法练习第二十五天| 216.组合总和III、17.电话号码的字母组合

算法练习第二十五天| 216.组合总和III、17.电话号码的字母组合

leetcode题目链接
17
216

216.组合总和III

class Solution {
    List<Integer> path = new ArrayList();
    List<List<Integer>> result = new ArrayList();
    public List<List<Integer>> combinationSum3(int k, int n) {
        backTrace(k,n,1,0);
        return  result;
    }
    public void backTrace(int k,int n,int startIndex,int sum){

        //结束条件
        if(path.size() == k){
            if(sum == n) result.add(new ArrayList(path));
            return;
        }

        for(int i = startIndex;i<=9-(k-path.size())+1;i++){
            sum += i;
            path.add(i);
            if (sum > n) { // 剪枝操作
                sum -= i; // 剪枝之前先把回溯做了
                path.removeLast(); // 剪枝之前先把回溯做了
                return;
            }
            backTrace(k,n,i+1,sum);
            sum -=i;
            path.removeLast();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

17.电话号码的字母组合

class Solution {
    List<String> result = new ArrayList();
    static Map<Integer,String> map = new HashMap();
    StringBuilder tmp = new StringBuilder();
    static {
        map.put(2,"abc");
        map.put(3,"def");
        map.put(4,"ghi");
        map.put(5,"jkl");
        map.put(6,"mno");
        map.put(7,"pqrs");
        map.put(8,"tuv");
        map.put(9,"wxyz");
    }
    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return result;
        }
        backTrace(digits,0);
        return result;
    }

    /**
        params:index遍历到第几个数字
     */
    public void backTrace(String digits,int index){
        //终止条件
        //这里为什么不是index==digits.length()-1???
        //需要理解遍历到这个最后的字符,和遍历完最后这个字符的区别
        if(index == digits.length()){
            result.add(tmp.toString());
            return;
        }
        int digit = digits.charAt(index) - '0';
        String s= map.get(digit);
        for(int i = 0;i<s.length();i++){
            tmp.append(s.charAt(i));
            backTrace(digits,index+1);
            tmp.deleteCharAt(tmp.length()-1);
        }

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/270462
推荐阅读
相关标签
  

闽ICP备14008679号