Day 22 - Leetcode 216组合总和III | Leetcode 17电话号码的字母组合

leetcode 216

题目链接
like leetcode 77

思路

  • 基本思路和leetcode 77 类似
  • 注意剪枝内容
    • 题目要求:Only numbers 1 through 9 are used.
    • 所以当树画到9 - (k-path.size())——还剩余能加入的数字
class Solution {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    LinkedList<Integer> path = new LinkedList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(k, n, 1);
        return res;
    }
    public void backtracking(int k, int n, int index) {
        if (path.size() == k) {
            if (sum == n)
                res.add(new ArrayList<>(path));
            return;
        }
		//for(int i = index; i <= 9; ++i)
        for (int i = index; i <= 9 - (k - path.size()) + 1; ++i) {
            sum += i;
            path.add(i);
            backtracking(k, n, i + 1);
            sum -= i;
            path.removeLast();
        }
    }
}

leetcode 17

题目链接

思路

  • 纵向递归深度 == digits.length()
  • 横向遍历——遍历的是每个数字所对应的string,like 2—"abc"
class Solution {
    List<String> res = new ArrayList<>();
    StringBuilder temp = new StringBuilder();

    public List<String> letterCombinations(String digits) {
        if (digits.length() == 0)
            return res;
        //把数字和字母对应存储
        String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        backTracking(digits, numString, 0);
        return res;

    }

    public void backTracking(String digits, String[] numString, int num) {
        if (num == digits.length()) {
            res.add(temp.toString());
            return;
        }
        //str 表示当前num对应的字符串
        String str = numString[digits.charAt(num) - '0'];
        for (int i = 0; i < str.length(); i++) {
            temp.append(str.charAt(i));
            backTracking(digits, numString, num + 1);
            //剔除末尾的继续尝试
            temp.deleteCharAt(temp.length() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值