代码随想录算法训练营第26天|39.组和总和、40.组和总和二、131.分割回文串

一、力扣39.组合总和

1.1 题目

在这里插入图片描述

1.2 思路

个人思路:组合问题,回溯:
(1)成员变量res,path,sum;
(2)由于每一个数字都可以被无限制重复选取,那么每次for循环时,candidates必须从头遍历到尾;(有逻辑错误,这样会导致res集合中出现重复的集合)
(3)递归终止条件:由于candidates元素介于2和40之间,那么当sum >= target时,return。
(4)回溯的时候不但要path回溯,同时不要忘记sum回溯。

看代码随想录后改进思路:
每次for循环时,不应该包含candidates的全部数据,因为这样会造成结果集的重复,比如
candidates:2 3 4;target:7。那么res中会存在223和232,这是同一种组合。
解决办法:每次for循环时的起始元素,还应当包含上层for循环所选取的元素。

1.3 代码

个人思路:(运行报错,原因是没有去重)

class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<Integer> path = new ArrayList<>();
    public int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //回溯
        backTracking(candidates,target);
        return res;

    }
    public void backTracking(int[] candidates,int target){
        //递归终止条件
        if(sum == target){
            res.add(new ArrayList<>(path));
            return;
        }else if(sum > target){
            return;
        }

        //单层递归+回溯
        for(int i =0;i<candidates.length;i++){
            path.add(candidates[i]);
            sum += candidates[i];

            backTracking(candidates,target);

            path.remove(path.size()-1);
            sum -= candidates[i];
        }
    }
}

在这里插入图片描述
修改后的代码:
加入startIndex,每一层递归时起始的数还应当包括上一层递归选取的数值;
backTracking(candidates,target,i);因为每个数据元素可以重用;

class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<Integer> path = new ArrayList<>();
    public int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //回溯
        backTracking(candidates,target,0);
        return res;

    }
    public void backTracking(int[] candidates,int target,int startIndex){
        //递归终止条件
        if(sum == target){
            res.add(new ArrayList<>(path));
            return;
        }else if(sum > target){
            return;
        }

        //单层递归+回溯
        for(int i =startIndex;i<candidates.length;i++){
            path.add(candidates[i]);
            sum += candidates[i];

            backTracking(candidates,target,i);

            path.remove(path.size()-1);
            sum -= candidates[i];
        }
    }
}

1.4 总结

本题卡壳关键:如何去重!,根本还是没有理解好组合与排列,组合只要是元素相同就是重复,与顺序无关。

二、力扣40.组合总和二

2.1 题目

在这里插入图片描述

2.2 思路

个人的思考:
(1)由于candidates中的每个数组在每个组合中只能使用一次,所以startIndex = i +1;
(2)递归终止条件仍然不变,即sum >= target;
(3)关键是本题candidates中的元素可能出现重复,如果按照之前的递归回溯套路,最终的res里可能会出现重复的组合,这就引出了去重的问题。
代码随想录去重:在主函数里先对candidates排序,然后在递归代码中实现去重逻辑;
在这里插入图片描述
上面箭头处的思路:if(num[i] == num[i-1] && used[i-1] == 0)简单来说就是对自己的子树不去重,但是对自己的兄弟要去重;

2.3 代码

class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<Integer> path = new ArrayList<>();
    public int sum = 0;
    public boolean[] used;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //used数组,记录元素是否被用过,默认为false,未用
        used = new boolean[candidates.length];
        for(int i = 0;i < candidates.length;i++){
            used[i] = false;
        }
        //先对原数组进行排序,方便去重
        Arrays.sort(candidates);

        backTracking(candidates,target,0);
        return res;
    
    }

    public void backTracking(int[] candidates,int target,int startIndex){
        //递归终止条件
        if(sum == target){
            res.add(new ArrayList<>(path));
            return;
        }
        if(sum > target){
            return;
        }

        //递归与回溯算法
        for(int i =startIndex;i<candidates.length;i++){
            //去重逻辑
            if(i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false){
                continue;
            }

            path.add(candidates[i]);
            sum += candidates[i];
            used[i] = true;

            backTracking(candidates,target,i+1);

            path.remove(path.size()-1);
            sum -= candidates[i];
            used[i] = false;
        }

    }
}

2.4 总结

比如说candidate里有一前一后两个重复的1,那么我前面这个1下面搜索的所有过程会把你后面这个1开头的所有组合的情况全都包含了。
关键:兄弟去重!(可以理解为是树的子孙去重(纵向)还是树的兄弟(横向)去重)
注意:数组工具类的常用方法:Arrays.sort(); Arrays.fill(数组,填充值);

三、力扣131.分割回文串

3.1 题目

在这里插入图片描述
回文串是向前和向后读都相同的字符串。

3.2 思路

关键点:
(1)分割其实也是组合问题,每一层分割其实就是一次组合;
(2)递归的终止条件:当startIndex == size,即return;
(3)startIndex就是切割线,[startIndex,i]这个范围就是在for循环中要要分割的子串范围,如果其中的某一次i区间符合回文串,那么加入path,然后继续向下调用backTracking算法,接下来执行回溯操作。
(4)实现判断是否是回文串的方法;(双指针法,从两边向中间走,比较字符是否相等)

3.3 代码

class Solution {
    public List<List<String>> res = new ArrayList<>();
    public List<String> path = new ArrayList<>();
    public List<List<String>> partition(String s) {
        //类似于组合问题
        backTracking(s,0);
        return res;

    }
    //回溯算法
    public void backTracking(String s,int startIndex){
        //递归的终止条件,直接加入res集合,我们在递归逻辑中来排除掉每一次分割的非回文串
        if(startIndex == s.length()){
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = startIndex;i< s.length();i++){
            if(isTrue(s,startIndex,i)){
                //[startIndex,i]是回文串,则加入path
                path.add(s.substring(startIndex,i+1));

                backTracking(s,i+1);

                path.remove(path.size()-1);
            }else{
                //不是回文串,则i++,继续尝试分割
                continue;
            }
        }
    }
    //判断是否回文串
    public boolean isTrue(String s,int left,int right){
        //双指针法
        while(left < right){
            if(s.charAt(left) != s.charAt(right)){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

3.4 总结

和组合问题类似,还需要好好体会其中的细节!

部分内容来自代码随想录:https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html

  • 29
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
算法训练营主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组,使得子数组的和大于等于给定的目标值。这里可以使用滑动窗口的方法来解决问题。使用两个指针来表示滑动窗口的左边界和右边界,通过移动指针来调整滑动窗口的大小,使得滑动窗口中的元素的和满足题目要求。具体实现的代码如下: ```python def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 right = 0 ans = float(&#39;inf&#39;) total = 0 while right < len(nums): total += nums[right] while total >= target: ans = min(ans, right - left + 1) total -= nums[left] left += 1 right += 1 return ans if ans != float(&#39;inf&#39;) else 0 ``` 以上就是第算法训练营的内容。通过这些题目的练习,可以提升对双指针和滑动窗口等算法的理解和应用能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值