美文网首页
LintCode:恢复IP地址【DFS】

LintCode:恢复IP地址【DFS】

作者: VickyShen | 来源:发表于2019-02-25 20:02 被阅读0次

    描述

    给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。
    (你的任务就是往这段字符串中添加三个点, 使它成为一个合法的IP地址. 返回所有可能的IP地址.)

    样例:

    输入: "25525511135"
    输出: ["255.255.11.135", "255.255.111.35"]
    解释: ["255.255.111.35", "255.255.11.135"] 同样可以.

    思路:

    ip地址特点:
    1.每一段范围为[0,255]。
    2.不能出现如01、023这种情况。
    用深度优先搜索DFS解决
    DFS:https://blog.csdn.net/ldx19980108/article/details/76324307
    深度优先搜索算法(英语:Depth-First-Search,简称DFS)是一种用于遍历或搜索树或图的算法。 沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点v的所在边都己被探寻过或者在搜寻时结点不满足条件,搜索将回溯到发现节点v的那条边的起始节点。整个进程反复进行直到所有节点都被访问为止。属于盲目搜索,最糟糕的情况算法时间复杂度为O(!n)。
    基本模板:

    int check(参数)
    {
        if(满足条件)
            return 1;
        return 0;
    }
    
    void dfs(int step)
    {
            判断边界
            {
                相应操作
            }
            尝试每一种可能
            {
                   满足check条件
                   标记
                   继续下一步dfs(step+1)
                   恢复初始状态(回溯的时候要用到)
            }
    } 
    
    public class RestoreIpAddresses426 {
    
        /**
         * 回溯法
         * 。要判断0<=value<=255且不能出现021这种情况
         * @param s
         */
        public static List<String> restoreIpAddresses2(String s) {
            // write your code here
            List<String> res = new ArrayList<>();
            if(s.length()<4||s.length()>12)
                return res;
    
            dfs(s,new ArrayList<>(),res,0);
            return res;
        }
    
        private static void dfs(String s,  List<String> list, List<String> res, int index) {
            //list中已存在4段数字字符串了,进入最终处理环节
            if(list.size()==4){
                if(index!=s.length()){
                    return;
                }
                StringBuilder ipAddress = new StringBuilder();
                for(String tmp:list){
                    ipAddress.append(tmp);
                    ipAddress.append(".");
                }
                ipAddress = ipAddress.deleteCharAt(ipAddress.length()-1);
                res.add(ipAddress.toString());
            }
            //以index为起点向后取数字,不超过s的长度而且最多取3个
            for(int i = index;i<s.length()&&i<index+3;i++){
                String tmp = s.substring(index,i+1);
                if(isVaildNumber(tmp)){
                    list.add(tmp);
                    dfs(s,list,res,i+1);
                    list.remove(list.size()-1);
                }
            }
    
        }
        private static boolean isVaildNumber(String s){
            if (s.charAt(0) == '0')
                return s.equals("0");       // to eliminate cases like "00", "10"
            int digit = Integer.valueOf(s);
            return digit >= 0 && digit <= 255;
        }
    
    
    
        public static void main(String[] args) {
            List<String> result = restoreIpAddresses2("101023");
        }
    }
    

    相关文章

      网友评论

          本文标题:LintCode:恢复IP地址【DFS】

          本文链接:https://www.haomeiwen.com/subject/cgcnyqtx.html