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

今天是第二十八天,前面几天的回溯算法不太熟,今天继续巩固

 

●  93.复原IP地址 

复制代码
class Solution {
    List<String> ret = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        LinkedList<String> path = new LinkedList<>();
        backTrace(0,s,path);
        return ret;
    }

    public void backTrace(int startIndex, String s, LinkedList<String> path){
        if(path.size() > 4) return; // 长度>4剪枝
        if(startIndex == s.length() && path.size() == 4){
            ret.add(toResult(path));
            return;
        }
        for(int i = startIndex;i<s.length();i++){
            String str = s.substring(startIndex,i+1);
            if(!isValid(str)) continue;
            path.offerLast(str);
            backTrace(i+1,s,path);
            path.removeLast();
        }
    }

    public String toResult(LinkedList<String> path){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < path.size(); i++){
            sb.append(path.get(i));
            if(i != path.size() - 1) 
                sb.append(".");
        }
        return sb.toString();
    }

    public boolean isValid(String s){
        if(s.length()==1) return true;
        if(s.length()>3) return false;
        if(s.charAt(0) == '0') return false;
        if(Integer.valueOf(s) > 255) return false;
        return true;
    }
}
复制代码

 

标准的回溯模版题

 

●  78.子集 

复制代码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        res.add(new ArrayList<>());
        for(int num : nums){
            int n = res.size();
            for(int i = 0; i<n; i++){
                List<Integer> temp = new ArrayList<>(res.get(i));
                temp.add(num);
                res.add(temp);
            }
        }
        return res;
    }
}
复制代码

可以有不用回溯的思路

●  90.子集II 

复制代码
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        
    List<List<Integer>> retList = new ArrayList<>();
    retList.add(new ArrayList<>());
    if(nums == null || nums.length == 0) return retList;
    Arrays.sort(nums);
    
    
    List<Integer> tmp = new ArrayList<>();
    tmp.add(nums[0]);
    retList.add(tmp);
    if(nums.length == 1) return retList;
    
    int lastLen = 1;
    
    for(int i = 1; i < nums.length; i++){
        int size = retList.size();
        if(nums[i] != nums[i-1]){
            lastLen = size;
        }
        
        for(int j = size - lastLen; j < size; j++){
            List<Integer> inner = new ArrayList(retList.get(j));
            inner.add(nums[i]);
            retList.add(inner);
        }
    }
    return retList;
}
    
}
复制代码

多了一步去重

 

今天的题三道题两道没有用回溯,过几天复习到的时候重新用回溯做一遍

posted @   小猫Soda  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示