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

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

 

●  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 @ 2022-11-09 15:21  小猫Soda  阅读(28)  评论(0)    收藏  举报