代码随想录算法训练营第二十二天-216组合总和III、17电话号码的字母组合
Kiml Lv5
  • 前言
    状态:216 可以 AC。17 看了部分解析写出来的。

  • 更新

1
24-06-10 初始记录

初步题解

216 组合总和 III

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

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
public class LE22 {  
public static void main(String[] args) {
List<List<Integer>> combinationSum3 = combinationSum3(9, 45);
for (List<Integer> integerList : combinationSum3) {
System.out.println(Arrays.toString(integerList.stream().mapToInt(n -> n).toArray()));
}
}

public static List<List<Integer>> combinationSum3(int k, int n) {
// 结果集
List<List<Integer>> result = new ArrayList<>();
// 单个结果
List<Integer> list = new ArrayList<>();

combinationSum(1, k, n, 0, list, result);
return result;
}

private static void combinationSum(int start, int k, int n, int sum, List<Integer> list, List<List<Integer>> result) {
// 剪枝操作
if (sum > n) {
return;
}

if (list.size() == k) {
if (sum == n) {
List<Integer> resultOne = new ArrayList<>(list);
result.add(resultOne);
}
return;
}

for (int j = start; j <= 9 - (k - list.size()) + 1; j++) {
list.add(j);
combinationSum(j + 1, k, n, sum + j, list, result);
list.remove(list.size() - 1);
}
}
}

17 电话号码的字母组合

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

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
/**  
* @param digits 按键数组
* @return 结果
*/
public static List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
String[] buttonList = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

if (digits == null || "".equals(digits)) {
return list;
}

combinations(0, digits, buttonList, "", list);
return list;
}

/**
* * @param i 遍历的层数
*/
private static void combinations(int i, String digits, String[] buttonList, String str, List<String> list) {
if (i == digits.length()) {
list.add(str);
return;
}

int digit = Integer.parseInt(digits.charAt(i) + "");
String letter = buttonList[digit];
for (int j = 0; j < letter.length(); j++) {
str+=letter.charAt(j);
combinations(i + 1, digits, buttonList, str, list);
str = str.substring(0, str.length() - 1);
}
}

看解析

216 组合总和 III

题目链接/文章讲解:(https://programmercarl.com/0216.组合总和III.html)

视频讲解:https://www.bilibili.com/video/BV1wg411873x

17 电话号码的字母组合

题目链接/文章讲解:(https://programmercarl.com/0017.电话号码的字母组合.html)

视频讲解:https://www.bilibili.com/video/BV1yV4y1V7Ug

 评论
评论插件加载失败
正在加载评论插件
由 Hexo 驱动 & 主题 Keep
访客数 访问量