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

216. 组合总和 III - 力扣(LeetCode)

class Solution {
    public List> combinationSum3(int k, int n) {
        List> res = new ArrayList<>();
        List list = new ArrayList<>();
        dfs(res, list, k, n, 1, 0);
        return res;
    }

    private void dfs(List> res, List list, int k, int n, int idx, int sum) {
        if (sum > n) return;

        if (list.size() == k) {
            if (sum == n) {
                res.add(new ArrayList<>(list));
            }
        }

        for (int i = idx; i <= 9; i++) {
            sum += i;
            list.add(i);
            dfs(res, list, k, n, i + 1, sum);
            sum -= i;
            list.remove(list.size() - 1);
        }
    }
}

17. 电话号码的字母组合 - 力扣(LeetCode)

class Solution {
    String[] keys = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    public List letterCombinations(String digits) {
        List res = new ArrayList<>();
        if (digits.isEmpty()) return res;
        StringBuilder sb = new StringBuilder();
        dfs(res, sb, digits, 0);
        return res;
    }

    private void dfs(List res, StringBuilder sb, String digits, int idx) {
        if (idx == digits.length()) {
            res.add(sb.toString());
            return;
        }

        String cur = keys[digits.charAt(idx) - '0'];
        for (int i = 0; i < cur.length(); i++) {
            sb.append(cur.charAt(i));
            dfs(res, sb, digits, idx + 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}

你可能感兴趣的:(代码随想录三刷,深度优先,算法,数据结构,java,leetcode)