LeeCode打卡第三十二天

LeeCode打卡第三十二天

第一题:组合总和II(LeeCode第40题):

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的每个数字在每个组合中只能使用 一次 。**注意:**解集不能包含重复的组合。

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> temp = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0);
        return res;
    }
    public void backTracking(int[] candidates, int target, int startIndex){
        int sum = 0;
        for(int n : temp) sum += n;
        if(sum > target){
            return;
        }
        if(sum == target){
            res.add(new ArrayList<>(temp));
            return;
        }
        for(int i = startIndex; i < candidates.length; i++){
            if(i > startIndex && candidates[i] == candidates[i - 1]) continue;
            temp.add(candidates[i]);
            backTracking(candidates, target, i + 1);
            temp.remove(temp.size() - 1);
        }
    }
}

第二题:分割回文串(LeeCode第131题):

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。。


主要思路:就是i注意回文子串的拼接,这里主要是用了StringBuilder的append方法实现的,再就是回文子串的判断,可以另写一个函数

class Solution {
    List<List<String>> res = new ArrayList<>();
    List<String> temp = new ArrayList<>();
    public List<List<String>> partition(String s) {
        backtracking(s, 0, new StringBuilder());
        return res;
    }
    void backtracking(String s, int startIndex, StringBuilder sb){
        if(startIndex == s.length()){
            res.add(new ArrayList<>(temp));
            return;
        }
        for(int i = startIndex; i < s.length(); i++){
            sb.append(s.charAt(i));
            if(check(sb)){
                temp.add(sb.toString());
                backtracking(s, i + 1, new StringBuilder());
                temp.remove(temp.size() - 1);
            }

        }
    }
    private boolean check(StringBuilder sb){
        for(int i = 0; i < sb.length()/2; i++){
            if(sb.charAt(i) != sb.charAt(sb.length() - i - 1)) return false;
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值