第七章 回溯算法part02

54 阅读1分钟

216. Combination Sum III

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

题目解析:

  • 回溯求所有组合

代码:

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> combs = new ArrayList<>();
        backtracking(1, 9, k, n, 0, new ArrayList<>(), combs);
        return combs;
    }

    public void backtracking(int start, int end, int k, int target, int sum, List<Integer> path, List<List<Integer>> combs) {
        if (path.size() == k) {
            if (sum == target) {
                combs.add(new ArrayList<>(path));
            }
            return;
        }
        
        for (int i = start; i <= end; i++) {
            path.add(i);
            sum += i;
            backtracking(i+1, end, k, target, sum, path, combs);
            sum -= i;
            path.remove(path.size() - 1);
        }
    }
}

17. Letter Combinations of a Phone Number

题目解析:

  • 回溯

代码:

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> combs = new ArrayList<>();
        if (digits.length() == 0) {
            return combs;
        }
        String[] board = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        backtracking(digits, 0, new StringBuilder(), board, combs);
        return combs;
    }

    public void backtracking(String digits, int start, StringBuilder path,  String[] board, List<String> combs) {
        if (start == digits.length()) {
            combs.add(path.toString());
            return;
        }
        String s = board[digits.charAt(start) - '2'];
        for (int i = 0; i < s.length(); i++) {
            path.append(s.charAt(i));
            backtracking(digits, start + 1, path, board, combs);
            path.deleteCharAt(path.length() - 1);
        }
    }
}