代码随想录Day025 | Leetcode 216.组合总和III 、Leetcode 17.电话号码的字母组合

216.组合总和III

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new LinkedList<>();
        Stack<Integer> stack = new Stack<>();
        process(res, stack, 1, 0, k, n);


        return res;
    }

    public void process(List<List<Integer>> res, Stack<Integer> stack, int cur, int sum, int k, int n) {
        if (sum == n && stack.size() == k) {
            List<Integer> linkedList = new LinkedList<>();
            Integer[] integers = stack.toArray(new Integer[stack.size()]);
            linkedList = Arrays.asList(integers);
            res.add(linkedList);

            return;
        }


        for (int i = cur; i <= 9; i++) {
            if (stack.size() == k || sum >= n) {
                continue;
            }
            stack.add(i);
            sum += i;
            process(res, stack, i + 1, sum, k, n);
            sum -= i;
            stack.pop();
        }

    }

}

17.电话号码的字母组合

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new LinkedList<>();

        if (digits == null || ("").equals(digits)) {
            return res;
        }
        String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuilder stringBuilder = new StringBuilder();
        process(res, digits, stringBuilder, numString, 0);
        return res;
    }

    public void process(List<String> res, String digits, StringBuilder stringBuilder, String[] numString, int cur) {
        if (cur == digits.length()) {
            res.add(stringBuilder.toString());
            return;
        }


        String str = numString[digits.charAt(cur) - '0'];
        for (int i = 0; i < str.length(); i++) {
            stringBuilder.append(str.charAt(i));
            process(res, digits, stringBuilder, numString, cur + 1);
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);

        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值