代码随想录算法训练营二十一天|回溯part03

LeetCode 93 复原IP地址

题目链接:93. 复原 IP 地址 - 力扣(LeetCode)

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:

输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]
示例 2:

输入:s = "0000"
输出:["0.0.0.0"]
示例 3:

输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

 这个问题和分割回文串一样,都是切割问题,抽象为树型结构如图所示:

 回溯函数参数:字符串s,起始位置startIndex

终止条件:字符串已经被分为四段

单层搜索的逻辑:和分割回文串相似(具体见我的上一篇博客)

代码如下:

class Solution {
    List<String> res=new ArrayList<>();
    List<String> list=new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        if(s.length()<4||s.length()>12)return res;
        backtracking(s,0);
        return res;
    }
    public void backtracking(String s,int startIndex){
        if(list.size()==4&&startIndex>=s.length()){
            StringBuffer sb=new StringBuffer();
            for(int i=0;i<list.size()-1;i++){
                sb.append(list.get(i));
                sb.append(".");
            }
            sb.append(list.get(list.size()-1));
            res.add(sb.toString());
            return;
        }
        for(int i=startIndex;i<s.length();i++){
            if(s.length()-startIndex>(4-list.size())*3||s.length()-startIndex<(4-list.size()))break;//剩余字符太多或太少都无法构成合法IP
            String s1=s.substring(startIndex,i+1);
            long num=Long.parseLong(s1);
            if(num>=0&&num<=255&&(s1.charAt(0)-'0'!=0||s1.length()==1)){//判断数字是否合法
                list.add(s1);
                backtracking(s,i+1);
                list.remove(list.size()-1);
            }
        }
    }
}

LeetCode 78 子集

题目链接:78. 子集 - 力扣(LeetCode)

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:

输入:nums = [0]
输出:[[],[0]]

 本题抽象为树型结构:

直接套回溯模板就行 :

class Solution {
    List<List<Integer>> res=new ArrayList<List<Integer>>();
    List<Integer> list=new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        res.add(new ArrayList<>(list));
        backtracking(nums,0);
        return res;
    }
    public void backtracking(int[] arr,int startIndex){
        for(int i=startIndex;i<arr.length;i++){
            list.add(arr[i]);
            res.add(new ArrayList<>(list));
            backtracking(arr,i+1);
            list.remove(list.size()-1);
        }
    }
}

LeetCode 90 子集II

题目链接:90. 子集 II - 力扣(LeetCode)

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。

解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

示例 1:

输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
示例 2:

输入:nums = [0]
输出:[[],[0]]

 这个题相当于是78.子集和40.组合总和II两道题的结合,一方面要递归求子集,一方面还要去重。

直接上代码,去重的思路上一篇博客已经说过了:

class Solution {
    List<List<Integer>> res=new ArrayList<List<Integer>>();
    List<Integer> list=new ArrayList<>();
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        res.add(new ArrayList<>(list));
        Arrays.sort(nums);
        backtracking(nums,0);
        return res;
    }
    public void backtracking(int[] arr,int startIndex){
        for(int i=startIndex;i<arr.length;i++){
            if(i>startIndex&&arr[i]==arr[i-1])continue;
            list.add(arr[i]);
            res.add(new ArrayList<>(list));
            backtracking(arr,i+1);
            list.remove(list.size()-1);
        }
    }
}

在之前回溯的基础之上,今天的三道题都很容易解出来。

第二十二天的算法训练营主要涵盖了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题,题目要求在给定的数组中找到长度最小的子数组,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值