zoukankan      html  css  js  c++  java
  • 93. Restore IP Addresses(dfs)

    Given a string containing only digits, restore it by returning all possible valid IP address combinations.

    For example:
    Given "25525511135",

    return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

    思路:IP address的规则:一共四段;每段的值不能超过255;不能以0开头,但可以在一段中只有数字0

    class Solution {
    public:
        vector<string> restoreIpAddresses(string s) {
            dfs(s, "", 1);
            return ret;
        }
        
        void dfs(string s, string currentIP, int depth){ //depth表示第几个section
            if(depth == 4){
                if(check(s)) 
                    ret.push_back(currentIP+s);
                return;
            }
            
            int len = s.length();
            if(len < 5-depth){ //剩余string长度过短
                return;
            }
            
            string s1, s2;
            //check if we can assign 3 digits in the section
            if(len > 3 ){
                s1 = s.substr(0,3);
                
                if(check(s1)){
                    s2 = s.substr(3);
                    dfs(s2,currentIP+s1+".", depth+1);
                }
            }
            
            //check if we can assign 2 digits in the section
            if(len > 2 ){
                s1 = s.substr(0,2);
                if(check(s1)){
                    s2 = s.substr(2);
                    dfs(s2,currentIP+s1+".", depth+1);
                }
            }
            
            //assign 1 digits in the section
            s2 = s.substr(1);
            dfs(s2,currentIP+s[0]+".", depth+1);
        }
        
        bool check(string section){
            int len = section.length();
            if(len == 0 || len > 3) return false;
            int value = stoi(section);
            if(len==3){
                if(section[0]!='0' && value <= 255) return true;
                else return false;
            }
            else if(len==2){
                if(section[0]=='0') return false;
                else return true;
            }
            return true;
        }
    private: 
        vector<string> ret;
    };

     当然也能用循环,每两个section之间的分割用一个for循环遍历分割的位置,一共是三重for循环。

  • 相关阅读:
    [一个64位操作系统的设计与实现] 3.1 Func_GetFATEntry疑惑
    【参考】 实现X86_64架构下的BootLoader(二)文件系统
    LBA和CHS转换(转)
    Grafana 重置admin密码
    linux-source: not found ubuntu执行脚本报错
    Hbase学习
    高并发理解
    Linux下安装Artemis
    SpringInAction 第八章 发送异步消息
    SpringInAction 六七章总结
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4855372.html
Copyright © 2011-2022 走看看