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

LeetCode 216. 组合总和 III
题目链接:216. 组合总和 III - 力扣(LeetCode)

​思路:

这道题的要求返回的组合不能有相同的,那么我们递归的每一次过程中,用一个for循环来遍历所有满足条件的放入临时数组path中,判断条件是:如果加数的个数正确了,和也等于目标数,就把当前内容添加一份至res。剪枝的过程就是没必要所有都判断。剩余加的数小了可以递归,否则break进入下一轮。

代码:

#python
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res, path = [], []
        if k == 0:
            return res
        def dfs(i):
            if sum(path) == n and len(path) == k:
                res.append(path.copy())
                return
            diff = n - sum(path)
            for j in range(i, 10):
                if j <= diff:
                    path.append(j)
                    dfs(j + 1)
                    path.pop()
        dfs(1)
        return res

/java
class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        traversal(1, n, k, res, path);
        return res;
    }

    private static void traversal(int cur_idx, int n, int k, List<List<Integer>> res, List<Integer> path){
        if(path.size() == k){
            int sum = 0;
            for(int i : path){
                sum += i;
            }
            if(sum == n){
                res.add(new ArrayList<>(path));
            }
            return;
        }
        if(n - cur_idx + 1 < k - path.size()){
            return;
        }
        for(int j = cur_idx; j <= 9; j++){
            path.add(j);
            traversal(j + 1, n, k, res, path);
            path.remove(path.size() - 1);
        }
    }
}

LeetCode 17. 电话号码的字母组合
题目链接:17. 电话号码的字母组合 - 力扣(LeetCode)

​思路:

重点是如何将每个数字按键与字母所对应起来,其实可以发现,键盘的数字和单个位置的数字相同,因此我们可以考虑用一个数组来存储键盘的字母,用其下标来表示号码的数字,在每一次遍历的时候,使用for循环遍历数组该位置的所有字母,并且添加至path中进行下一轮递归。边界中止条件是当输入的数字长度与临时数组的长度相等时。

代码:

#python
match = ['', '','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if digits == "":
            return []
        digits = list(map(int, digits))
        res, path = [], []
        def dfs(i):
            if len(digits) == len(path):
                res.append(''.join(path))
                return
            for x in match[digits[i]]:
                path.append(x)
                dfs(i + 1)
                path.pop()
        dfs(0)
        return res
/java
class Solution {
    public List<String> letterCombinations(String digits) {
        if(digits.equals("")){
            return new ArrayList<>();
        }
        char[] words = digits.toCharArray();
        List<String> res = new ArrayList<>();
        Deque<Character> path = new ArrayDeque<>();
        Map<Character, List<Character>> map = new HashMap<>();
        map.put('2', Arrays.asList('a', 'b', 'c'));
        map.put('3', Arrays.asList('d', 'e', 'f'));
        map.put('4', Arrays.asList('g', 'h', 'i'));
        map.put('5', Arrays.asList('j', 'k', 'l'));
        map.put('6', Arrays.asList('m', 'n', 'o'));
        map.put('7', Arrays.asList('p', 'q', 'r', 's'));
        map.put('8', Arrays.asList('t', 'u', 'v'));
        map.put('9', Arrays.asList('w', 'x', 'y', 'z'));
        traversal(0, words, res, path, map);
        return res;
    }

    private static void traversal(int cur_idx, char[] words, List<String> res, Deque<Character> path, Map<Character, List<Character>> map){
        if(cur_idx == words.length){
            StringBuilder sb = new StringBuilder();
            for(char ch : path){
                sb.append(ch);
            }
            res.add(sb.toString());
            return;
        }
        for(char ch : map.get(words[cur_idx])){
            path.offerLast(ch);
            traversal(cur_idx + 1, words, res, path, map);
            path.pollLast();
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别看了真C不了一点

打赏者皆为义父

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值