Day 25 | 回溯 216.组合总和III 、17.电话号码的字母组合

216.组合总和III

题目
文章讲解
视频讲解

思路:

以回溯函数做对称,上面做了什么操作,下面也是

java 复制代码
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

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

    private void travelsal(int k, int n, int startIndex, int sum) {
        if (sum == n && path.size() == k) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
            if (sum > n || path.size() > k)
                break;
            path.add(i);
            sum += i;
            travelsal(k, n, i + 1, sum);
            sum -= i;
            path.removeLast();
        }
    }
}

17.电话号码的字母组合

题目
文章讲解
视频讲解

思路:思路上和组合很像,不同的是对字符串进行操作

java 复制代码
class Solution {
    List<String> list = new ArrayList<>();

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0)
            return list;
        String[] numString = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
        travelsal(digits, numString, 0);
        return list;
    }

    StringBuilder temp = new StringBuilder();

    public void travelsal(String digits, String[] numString, int num) {
        if (num == digits.length()) {
            list.add(temp.toString());
            return;
        }

        String str = numString[digits.charAt(num) - '0'];

        for (int i = 0; i < str.length(); i++) {
            temp.append(str.charAt(i));
            travelsal(digits, numString, num + 1);
            temp.deleteCharAt(temp.length() - 1);
        }
    }
}

还得再想想

相关推荐
YDS82940 分钟前
DeepSeek RAG&MCP + Agent智能体项目 —— 集成ELK日志管理系统和Prometheus监控系统
java·elk·ai·springboot·agent·prometheus·deepseek
骄马之死8 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
Frostnova丶8 小时前
【算法笔记】数学知识
笔记·算法
吴可可1239 小时前
AutoCAD 2016与2014二次开发关键差异
算法
郑洁文9 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
雨白10 小时前
哈希:以时间换空间的算法实战
算法
螺丝钉code10 小时前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
摇滚侠11 小时前
Maven 入门+高深 单一架构案例 54-59
java·架构·maven·intellij-idea
VidDown11 小时前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman