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;
    }
};
相关推荐
Shilong Wang几秒前
MLE, MAP, Full Bayes
人工智能·算法·机器学习
Theodore_10224 分钟前
机器学习(6)特征工程与多项式回归
深度学习·算法·机器学习·数据分析·多项式回归
知花实央l4 分钟前
【算法与数据结构】拓扑排序实战(栈+邻接表+环判断,附可运行代码)
数据结构·算法
lingling00911 分钟前
机械臂动作捕捉系统选型指南:从需求到方案,NOKOV 度量光学动捕成优选
人工智能·算法
吃着火锅x唱着歌21 分钟前
LeetCode 410.分割数组的最大值
数据结构·算法·leetcode
Benny_Tang43 分钟前
题解:P7989 [USACO21DEC] Bracelet Crossings G
c++·算法
YSRM1 小时前
Leetcode+Java+图论+最小生成树&拓扑排序
java·leetcode·图论
YSRM1 小时前
Leetcode+Java+图论+并查集
算法·leetcode·图论
小白杨树树1 小时前
【C++】力扣hot100错误总结
c++·leetcode·c#