LeetCode 刷题【93. 复原 IP 地址】

93. 复原 IP 地址

自己做

解:回溯法

cpp 复制代码
class Solution {
private:
    vector<string> res;

public:
    void tryIpAddresses(string &s, int index, int i, string &ip){           //index代表s的下标索引,i代表是第几段IP地址(分四段),ip即是保存的结果
        if((int)s.size() - index > (4 - i) * 3 )                            //取不完完整的IP地址,比如最多取12位(3 * 4),但是字符串却有20位,这时候就取不完了,必然组不成IP地址
            return;

        if(ip.size() - 1 == s.size() + 3 && i == 4){                       //保存结果【已经取完四段IP地址】
            ip.pop_back();                                                 //弹出'.'
            res.push_back(ip);
            ip.push_back('.');
            return;
        }

        //尝试取一位
        ip.push_back(s[index]);
        ip.push_back('.');
        tryIpAddresses(s, index + 1, i + 1, ip);
        ip.pop_back();
        ip.pop_back();

        //尝试取两位
        if(index + 1 < (int)s.size() && s[index] > '0'){
            ip.push_back(s[index]);
            ip.push_back(s[index + 1]);
            ip.push_back('.');
            tryIpAddresses(s, index + 2, i + 1, ip);
            ip.pop_back();
            ip.pop_back();
            ip.pop_back();
        }
        
        //尝试取三位
        if(index + 2 < (int)s.size() && 
        (s[index] == '1' || 
        s[index] == '2' && s[index + 1] == '5' && s[index + 2] <= '5' || 
        s[index] == '2' && s[index + 1] < '5')){
            ip.push_back(s[index]);
            ip.push_back(s[index + 1]);
            ip.push_back(s[index + 2]);
            ip.push_back('.');
            tryIpAddresses(s, index + 3, i + 1, ip);
            ip.pop_back();
            ip.pop_back();
            ip.pop_back();
            ip.pop_back();
        }
        
    }

    vector<string> restoreIpAddresses(string s) {
        string str;
        tryIpAddresses(s, 0, 0, str);
        return res;
    }
};
相关推荐
NAGNIP7 小时前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP7 小时前
一文搞懂机器学习中的特征构造!
算法·面试
Learn Beyond Limits8 小时前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp
你怎么知道我是队长8 小时前
C语言---typedef
c语言·c++·算法
Qhumaing9 小时前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
踩坑记录11 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
Z1Jxxx11 小时前
01序列01序列
开发语言·c++·算法
汽车仪器仪表相关领域12 小时前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试
Doro再努力13 小时前
【数据结构08】队列实现及练习
数据结构·算法