[leetcode]93. Restore IP Addresses

本文介绍了一种通过深度优先搜索解决LeetCode上恢复IP地址问题的算法。该算法使用递归函数来寻找所有可能的有效IP地址组合,并确保每个部分都符合IP地址规范。此外,还提供了一个基于遍历所有可能组合的方法,通过直接计算各段数值来判断是否为有效IP。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/restore-ip-addresses/tabs/description

 

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)

 

 

 

class Solution {
private:
    void dfs(string &s,vector<string>&res,int startidx,string mstr,int depth)
    {
        if(depth>4)
            return;
        if(depth==4&&startidx==s.length())
            res.push_back(mstr);
        else
        {
            for(int i=1;i<4;i++)
            {
                if(startidx+i>s.length()) break;
                string subs=s.substr(startidx,i);
                if((subs[0]=='0'&&i>1)||(stoi(subs)>=256&&i==3))
                    continue;
                dfs(s,res,startidx+i,mstr+subs+(depth==3?"":"."),depth+1);
            }
        }
    }
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        dfs(s,res,0,"",0);
        return res;
    }
};

 

 

 

 

 

 

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        string ans;

        for(int a=1;a<=3;a++)
        {
            for(int b=1;b<=3;b++)
            {
                for(int c=1;c<=3;c++)
                {
                    for(int d=1;d<=3;d++)
                    {
                        if(a+b+c+d==s.length())
                        {
                            int A=stoi(s.substr(0,a));
                            int B=stoi(s.substr(a,b));
                            int C=stoi(s.substr(a+b,c));
                            int D=stoi(s.substr(a+b+c,d));
                            if(A<=255 && B<=255 && C<=255 && D<=255)
                            {
                                ans=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D);
                                if(ans.length()==s.length()+3)
                                {
                                    res.push_back(ans);
                                }
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
};

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值