LeeCode打卡第三十一天

LeeCode打卡第三十一天

第一题:电话号码的字母组合(LeeCode第17题):

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

主要思想:最重要的一个点是,最后输出的为一个字符串数组,所以每一个字符串的保存很重要,本题解主要用String builder中的字符串的拼接方法来实现的。

class Solution {
    List<String> res = new ArrayList<>();
    StringBuilder temp = new StringBuilder();
    public List<String> letterCombinations(String digits) {
        if(digits == null || digits.length() == 0) return res;
        String[] numString = {"", "", "abc", "def","ghi", "jkl", "mno", "pqrs", "tuv","wxyz"};
        backtracking(digits, numString, 0);
        return res;
    }
    void backtracking(String digits, String[] numString, int num){
        if(num == digits.length()){
            res.add(temp.toString());
            return;
        }
        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);
        }
    }
}

第二题:数组总和(LeeCode第39题):

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 对于给定的输入,保证和为 target 的不同组合数少于 150 个。


class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> temp = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, 0);
        return res;
    }
    void backtracking(int[] candidates, int target, int sum, int startIndex){
        if(sum > target) return;
        if(sum == target){
            res.add(new ArrayList<>(temp));
            return;
        }
        for(int i = startIndex; i < candidates.length; i++){
            sum += candidates[i];
            temp.add(candidates[i]);
            backtracking(candidates, target, sum, i);
            sum -= candidates[i];
            temp.remove(temp.size() - 1);
        }
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值