Restore IP Addresses

本文介绍了一种使用回溯法解决IP地址恢复问题的方法。通过递归地决定在字符串中的哪些位置添加点来生成所有可能的有效IP地址组合。文章详细解释了实现过程中的关键步骤和注意事项。

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)

这道题刚一看,感觉没什么思路,后面看了下提醒,顿时就醒悟了,这就是经典的回溯题。回溯的情况就两种,就是在某个数字时候,是否应该加‘.’号,加是一种情况,不加又是另外一种情况,所以思路一下就有了。有了思路不一定可以正确的解决,这道题要考虑的细节特别多;首先就是,要考虑0开头的分段应该舍弃(前提是这个分段长度大于1),还有一个就是递归结束条件的判断,这里分不满足条件的明显错误的结束,还有就是满足条件的不符合分段要求的结束,最后才是满足条件的结束。搞清楚这几个问题之后,才能正确的解决这个问题;

class Solution {
public:
    //递归回溯法
    void restoreIp(string s, int curIndex, int dotNum, string curSub, string tmpIp, vector<string> &Res)
    {
        int len = s.size();
        if(atoll(curSub.c_str()) > 255 || dotNum > 3 || curIndex >= len)
        {
            return;
        }
        
        if(dotNum == 3)
        {
            if(curIndex == s.size() - 1 && curSub.size() > 0)
            {
                tmpIp += curSub;
                Res.push_back(tmpIp);
                return;
            }
            
            curSub += s.substr(curIndex + 1, s.size() - curIndex - 1);
            if(atoll(curSub.c_str()) <= 255 && (curSub.size() == 1 || (curSub.size() > 1 && curSub[0] != '0')))
            {
                tmpIp += curSub;
                Res.push_back(tmpIp);
            }
            return;
        }
        
        if(curIndex + 1 < len)
        {
            //不断开
            if((curSub.size() == 0 && s[curIndex + 1] == '0')
            || (curSub.size() > 0 && curSub[0] == '0'))
            {
                ;
            }
            else
            {
                curSub += s[curIndex + 1];
                restoreIp(s, curIndex + 1, dotNum, curSub, tmpIp, Res);
                curSub.pop_back(); //回溯
            }
            
            //断开
            tmpIp += curSub + '.';
            string tmpSub = "";
            tmpSub += s[curIndex + 1];
            restoreIp(s, curIndex + 1, dotNum + 1, tmpSub , tmpIp, Res);
        }
    }
    
    vector<string> restoreIpAddresses(string s) {
        int len = s.size();
        vector<string> Res;
        if(len < 4)
        {
            return Res;
        }
        
        string curSub = "";
        curSub += s[0];
        string tmpIp = "";
        restoreIp(s, 0, 0, curSub, tmpIp, Res);
        return Res;
    }
};


#include <iostream> #include <vector> #include <string> using namespace std; // 手动判断子串是否合法,并转为整数(避免 stoi 和 substr) bool isValidPart(const string& s, int start, int len) { if (len == 0 || len > 3) return false; if (len > 1 && s[start] == '0') return false; // 前导零非法 int num = 0; for (int i = 0; i < len; ++i) { char c = s[start + i]; if (c < '0' || c > '9') return false; // 非数字字符(其实题目保证只有数字) num = num * 10 + (c - '0'); } return num <= 255; } // 获取所有有效 IP 地址(无 substr,纯索引操作) vector<string> restoreIpAddresses(const string& s) { vector<string> result; int n = s.size(); // 剪枝:长度必须在 [4,12] if (n < 4 || n > 12) return result; // 枚举三段长度:l1, l2, l3(每段 1~3) for (int l1 = 1; l1 <= 3; ++l1) { if (l1 >= n) break; for (int l2 = 1; l2 <= 3; ++l2) { if (l1 + l2 >= n) break; for (int l3 = 1; l3 <= 3; ++l3) { int l4 = n - l1 - l2 - l3; if (l4 <= 0 || l4 > 3) continue; // 检查四段合法性 if (!isValidPart(s, 0, l1)) continue; if (!isValidPart(s, l1, l2)) continue; if (!isValidPart(s, l1+l2, l3)) continue; if (!isValidPart(s, l1+l2+l3, l4)) continue; // 手动构造结果字符串(避免多次 string 拼接开销) string ip; ip.reserve(16); // IP 最长如 "255.255.255.255" → 15 字符 // 第一段 for (int i = 0; i < l1; ++i) ip += s[i]; ip += '.'; // 第二段 for (int i = l1; i < l1+l2; ++i) ip += s[i]; ip += '.'; // 第三段 for (int i = l1+l2; i < l1+l2+l3; ++i) ip += s[i]; ip += '.'; // 第四段 for (int i = l1+l2+l3; i < n; ++i) ip += s[i]; result.push_back(ip); } } } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { string s; cin >> s; vector<string> ips = restoreIpAddresses(s); if (ips.empty()) { cout << "-1\n"; } else { for (const string& ip : ips) { cout << ip << '\n'; } } } return 0; } 这个好像有点问题
最新发布
11-16
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值