代码随想录算法训练营 Day 25 | 216.组合总和III,17.电话号码的字母组合

216.组合总和III

讲解链接:代码随想录-216.组合总和III

public List> combinationSum3(int k, int n) {
    List> result = new ArrayList<>();
    backtracking(k, n, 1, new ArrayList<>(), result);
    return result;
}


void backtracking(int k, int n, int startIndex, List paths, List> result) {
    int sum = 0;
    for (int i = 0; i < paths.size(); i++) {
        sum += paths.get(i);
    }
    if (paths.size() == k) {
        if (sum == n) {
            result.add(new ArrayList<>(paths));
        }
        return;
    }
    for (int i = startIndex; i <= 9; i++) {
        if (n - sum < i) {
            return;
        }
        paths.add(i);
        backtracking(k, n, i + 1, paths, result);
        paths.remove(paths.size() - 1);
    }
}

17.电话号码的字母组合

讲解链接:代码随想录-17.电话号码的字母组合

String[] keys = new String[]{
        "",
        "",
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz",
};

public List letterCombinations(String digits) {
    List result = new ArrayList<>();
    if (digits == null || digits.length() == 0) return result;
    backtracking(digits, 0, new StringBuilder(), result);
    return result;
}

void backtracking(String digits, Integer startIndex, StringBuilder paths, List result) {
    if (paths.length() == digits.length()) {
        result.add(new String(paths));
        paths = new StringBuilder();
        return;
    }
    int digit = Integer.valueOf(new Character(digits.charAt(startIndex)).toString());
    String letters = keys[digit];
    for (int i = 0; i < letters.length(); i++) {
        paths.append(letters.charAt(i));
        backtracking(digits, startIndex + 1, paths, result);
        paths.deleteCharAt(paths.length() - 1);
    }

}

你可能感兴趣的:(java,算法,数据结构)