restore-ip-addresses

来源:互联网 发布:微信 for windows 编辑:程序博客网 时间:2024/06/15 17:06

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)

这个题太复杂了
利用dfs;
这棵树是一个三叉树,ip地址前三段确定之后最后一段就确定了不再是三叉树,所以要把第三段和最后一段一起考虑.

class Solution {public:    vector<string> restoreIpAddresses(string s) {        if(s.size()<4||s.size()>12)            return vector<string>{};        vector<string> res;        string tmp;        recurbuild(res,s,0,tmp,0,s.size());        return res;    }    void recurbuild(vector<string>& res,string &s,int begin,string &tmp,int count,int limit)        {         string str=tmp;    //保留上一层路径的节点        if(count==0){            for(int i=1;i<=3;++i){                if(i==1||i>1&&s[begin]!='0'&&atoi(s.substr(begin,i).c_str())<=255){                tmp+=s.substr(begin,i);                tmp+='.';                recurbuild(res,s,begin+i,tmp,count+1,limit-i);                tmp=str;              //还原                }            }        }        else if(count==1&&limit>=3&&limit<=9)               {            for(int i=1;i<=3;++i){                if(i==1||i>1&&s[begin]!='0'&&atoi(s.substr(begin,i).c_str())<=255){                tmp+=s.substr(begin,i);                tmp+='.';                recurbuild(res,s,begin+i,tmp,count+1,limit-i);                tmp=str;                }            }        }        else if(count==2&&limit>=2&&limit<=6)              {            for(int i=1;i<=min(3,limit-1);++i){                if(i==1||i>1&&s[begin]!='0'&&atoi(s.substr(begin,i).c_str())<=255){                    if(s[begin+i]=='0'&&s.size()-begin-i>1||s.size()-begin-i>3||atoi(s.substr(begin+i,s.size()-begin-i).c_str())>255)                        continue;                tmp+=s.substr(begin,i);                tmp+='.';                               tmp+=s.substr(begin+i,s.size()-begin-i);                res.push_back(tmp);                tmp=str;                }            }        }    }};
0 0
原创粉丝点击