代码随想录算法训练营第二二天| 回溯算法理论基础 77. 组合 216.组合总和III 17.电话号码的字母组合

今日任务

回溯算法理论基础 
77. 组合 
216.组合总和III 
17.电话号码的字母组合 

回溯算法理论基础 

只要有递归就会有回溯。回溯法的本质是穷举,因此效率比较低,因为没得选,只能用回溯法。


77. 组合  

题目链接: . - 力扣(LeetCode)

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

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

    public  void combineHelper(int n, int k, int startIndex) {
        if (path.size() == k) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= n; i++) {
            path.add(i);
            combineHelper(n, k, i + 1);
            path.removeLast();
        }
    }
}

216.组合总和III 

题目链接: . - 力扣(LeetCode)

class Solution {

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

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

    public void restrospective(int k, int n, int startIndex){
        if (path.size() == k) {
            if (path.stream().mapToInt(Integer::intValue).sum() == n) {
                result.add(new ArrayList<>(path));
            }
            return;
        }
        for (int i = startIndex; i < 10; i++) {
            path.add(i);
            restrospective(k, n, i + 1);
            path.remove(path.size() - 1);
        }
        return;
    }
}

17.电话号码的字母组合 

题目链接: . - 力扣(LeetCode)

class Solution {

    List<String> result = new ArrayList<>();
    Map<Character, String> map = new HashMap<Character, String>();
    StringBuilder path = new StringBuilder();
    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {return result;}
        map.put('2',"abc");
        map.put('3',"def");
        map.put('4',"ghi");
        map.put('5',"jkl");
        map.put('6',"nmo");
        map.put('7',"pqrs");
        map.put('8',"tuv");
        map.put('9',"wxyz");
        restrospective(digits, 0);
        return result;
    }

     public void restrospective(String digits, int startIndex) {
        if (path.length() ==  digits.length()) {
            result.add(new String(path));
            return;
        }
        String str = map.get(digits.charAt(startIndex));
        for (int i = 0; i < str.length(); i++) {
            path.append(str.charAt(i));
            restrospective(digits, startIndex + 1);
            path.deleteCharAt(path.length() - 1);
        }
        return;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值