代码随想录训练营第二十三天| 39. 组合总和 40.组合总和II 131.分割回文串

39. 组合总和

题目链接/文章讲解: 代码随想录
//组合问题要考虑是不是在一个集合里操作
//最常见的就是递归回溯法
//再考虑考虑剪枝
class Solution{
    public List<List<Integer>> combinationSum(int[] candidates, int target){
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(candidates);//先进行排序
        backtracking(ans, new ArrayList<>(), candidates, target, 0, 0);
        return ans;
    }

    public void backtracking(List<List<Integer>> ans, List<Integer> path, int[] candidates, int target, int sum, int index){
        //找到了数字和为target的组合
        //剪枝一下 如果当前sum + candidate[i] > target 可以直接不进行递归 不必多余判断
        if(sum == target){
            ans.add(new ArrayList<>(path));
            return;
        }

        for(int i = index; i < candidates.length && candidates[i] + sum <= target; i++){
            path.add(candidates[i]);
            backtracking(ans, path, candidates, target, sum + candidates[i], i);
            path.remove(path.size() - 1);//回溯 移除路径path最后一个元素
        }
    }
}

感觉稍微自己能理解一下回溯了 能跟着循环走一遍思路 对每个位置应该有的参数有了想法

 40.组合总和II

题目链接/文章讲解: 代码随想录

 集合里有重复元素 但是不能选出的组合不能有重复的 此时就要对 树层进行剪枝 树枝不需要剪枝

Java代码:

class Solution {
    LinkedList<Integer> path = new LinkedList<>();
    List<List<Integer>> ans = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //先排序后递归剪枝回溯
        Arrays.sort(candidates);
        backtracking(candidates, target, 0);
        return ans;
    }

    private void backtracking(int[] candidates, int target, int startindex){
        if(sum == target){
            ans.add(new ArrayList<>(path));
            return;
        }
        for(int i = startindex; i < candidates.length && candidates[i] + sum <= target; i++){
            //接下来树层剪枝 跳过同一树层的剪枝
            if(i > startindex && candidates[i] == candidates[i - 1]){
                continue;
            }
            sum += candidates[i];
            path.add(candidates[i]);
            // i + 1 代表当前组内元素只选一次 不重复选择
            backtracking(candidates, target, i + 1);

            int temp = path.getLast();
            sum -= temp;//回溯
            path.removeLast();
        }
    }
}

 131.分割回文串

题目链接:131. 分割回文串 - 力扣(LeetCode)

讲解链接:代码随想录

这道题重点在于什么是分割 怎么转化为组合 怎么分割 怎么在递归循环里截取子串 子串里是否回文 需要多加练习

Java代码:

class Solution{
    List<List<String>> ans = new ArrayList<>();
    List<String> str = new ArrayList<>();
    public List<List<String>> partition(String s){
        backtracking(s, 0, new StringBuilder());
        return ans;
    }
    private void backtracking(String s, int startindex, StringBuilder sb){
        //因为起始位置一个一个加 所以结束时startindex一定等于s.length,
        //因为进入backtracking时
        //一定末尾也是回文 所以str是满足条件的
        if(startindex == s.length()){   
            ans.add(new ArrayList<>(str));
            return;
        }
        //从后往前搜索 如果发现回文 进入backtracking 起始位置后移动一位 循环结束
        for(int i = startindex ; i < s.length(); i++){
            sb.append(s.charAt(i));
            if(check(sb)){
                str.add(sb.toString());
                backtracking(s, i + 1, new StringBuilder());
                str.remove(str.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;
    }
}

第二十二算法训练营主要涵盖了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 ``` 以上就是第二十二算法训练营的内容。通过这些题目的练习,可以提升对双指针和滑动窗口等算法的理解和应用能力。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值