代码随想录训练营二刷第二十五天 | 216.组合总和III 17.电话号码的字母组合

代码随想录训练营二刷第二十五天 | 216.组合总和III 17.电话号码的字母组合

一、216.组合总和III

题目链接:https://leetcode.cn/problems/combination-sum-iii/

思路:模板题

java 复制代码
class Solution {
    List<List<Integer>> arrayList = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum3(int k, int n) {
        backTracking(k, n, 1);
        return arrayList;
    }
    void backTracking(int k, int n, int index) {
        if (list.size() < k && sum > n) return;
        if (list.size() == k && sum == n) {
            arrayList.add(new ArrayList<>(list));
            return;
        }
        for (int i = index; i <= 9; i++) {
            list.add(i);
            sum += i;
            backTracking(k, n, i+1);
            list.remove(list.size()-1);
            sum -= i;
        }
    }
}

二、17.电话号码的字母组合

题目链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/

思路:每次递归选取的集合需要改变

java 复制代码
class Solution {
    List<String> list = new ArrayList<>();
    StringBuilder builder = new StringBuilder();
    public List<String> letterCombinations(String digits) {
        if (digits.length() == 0) return list;
        String[] init = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        String[] strList = new String[digits.length()];
        for (int i = 0; i < digits.length(); i++) {
            strList[i] = init[digits.charAt(i) - '0'];
        }
        backTracking(strList, 0);
        return list;
    }
    void backTracking(String[] strList, int index) {
        if (builder.length() == strList.length) {
            list.add(builder.toString());
            return;
        }
        String strings = strList[index];
        for (int i = 0; i < strings.length(); i++) {
            builder.append(strings.charAt(i));
            backTracking(strList, index + 1);
            builder.deleteCharAt(index);
        }
    }
}
相关推荐
炼金士1 天前
基于多智能体技术的码头车辆最快行驶路径方案重构
算法·路径规划·集装箱码头
小刘max1 天前
最长递增子序列(LIS)详解:从 dp[i] 到 O(n²) 动态规划
算法·动态规划
王璐WL1 天前
【数据结构】双向链表
数据结构
谢景行^顾1 天前
数据结构知识掌握
linux·数据结构·算法
ShineWinsu1 天前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
DuHz1 天前
基于时频域霍夫变换的汽车雷达互干扰抑制——论文阅读
论文阅读·算法·汽车·毫米波雷达
hetao17338371 天前
ZYZ28-NOIP模拟赛-Round4 hetao1733837的record
c++·算法
Nebula_g1 天前
C语言应用实例:解方程(二分查找)
c语言·开发语言·学习·算法·二分查找·基础
少许极端1 天前
算法奇妙屋(十)-队列+宽搜(BFS)
java·数据结构·算法·bfs·宽度优先·队列
异步的告白1 天前
C语言-数据结构-1-动态数组
c语言·数据结构·c++