写点什么

代码随想录 Day25 - 回溯(二)

作者:jjn0703
  • 2023-07-23
    江苏
  • 本文字数:1635 字

    阅读完需:约 5 分钟

216. 组合总和 III

关键点在于 startIndex,通过该变量控制回溯的决策阶段。

package jjn.carl.backtrack;
import java.util.ArrayList;import java.util.List;
/** * @author Jiang Jining * @since 2023-07-23 22:19 */public class LeetCode216 { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> result = new ArrayList<>(); backtrack(k, n, new ArrayList<>(), result, 0, 1); return result; } private void backtrack(int k, int n, List<Integer> path, List<List<Integer>> result, int sum, int startIndex) { if (path.size() > k || sum > n) { return; } if (path.size() == k && sum == n) { result.add(new ArrayList<>(path)); return; } for (int i = startIndex; i < 10; i++) { path.add(i); sum += i; backtrack(k, n, path, result, sum, i + 1); path.remove(path.size() - 1); sum -= i; } } public static void main(String[] args) { System.out.println("new LeetCode216().combinationSum3(3, 7) = " + new LeetCode216().combinationSum3(3, 7)); System.out.println("new LeetCode216().combinationSum3(3, 9) = " + new LeetCode216().combinationSum3(3, 9)); }}
复制代码


17. 电话号码的字母组合

构造一个 KV 键值对,把每个键及对应的字母关系存储起来,随后回溯,每一个阶段取输入对应的可选项。

package jjn.carl.backtrack;
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Scanner;
/** * @author Jiang Jining * @since 2023-07-23 22:43 */public class LeetCode17 { private static final Map<Character, List<String>> KEY_MAP = Map.of('2', List.of("a", "b", "c"), '3', List.of("d", "e", "f"), '4', List.of("g", "h", "i"), '5', List.of("j", "k", "l"), '6', List.of("m", "n", "o"), '7', List.of("p", "q", "r", "s"), '8', List.of("t", "u", "v"), '9', List.of("w", "x", "y", "z")); public List<String> letterCombinations(String digits) { List<String> result = new ArrayList<>(); if (digits.length() == 0) { return result; } backtrack(digits, new StringBuilder(), result, 0); return result; } private void backtrack(String digits, StringBuilder stringBuilder, List<String> result, int startIndex) { if (stringBuilder.length() > digits.length()) { return; } if (stringBuilder.length() == digits.length()) { result.add(stringBuilder.toString()); return; } for (int i = startIndex; i < digits.length(); i++) { char c = digits.charAt(i); List<String> options = KEY_MAP.get(c); for (String option : options) { stringBuilder.append(option); backtrack(digits, stringBuilder, result, i + 1); stringBuilder.deleteCharAt(stringBuilder.length() - 1); } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String digits = scanner.nextLine(); List<String> result = new LeetCode17().letterCombinations(digits); System.out.println("result = " + result); }}
复制代码


发布于: 刚刚阅读数: 3
用户头像

jjn0703

关注

Java工程师/终身学习者 2018-03-26 加入

USTC硕士/健身健美爱好者/Java工程师.

评论

发布
暂无评论
代码随想录Day25 - 回溯(二)_jjn0703_InfoQ写作社区