Restore IP Addresses

来源:互联网 发布:淘宝网在哪里领红包 编辑:程序博客网 时间:2024/06/07 00:19

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)


Solution:

class Solution {public:    void dfs(vector<string> &res, const string s, int depth, const string &ip, int index)    {        if(s.length() == index && depth == 4)        {            res.push_back(ip.substr(1));        }        if(index >= s.length()) return;        if(index < s.length())        {            string str = s.substr(index, 1);            dfs(res, s, depth + 1, ip + "." + str, index + 1);        }        if(index + 1 < s.length())        {            string str = s.substr(index, 2);            if(str[0] != '0') dfs(res, s, depth + 1, ip + "." + str, index + 2);        }        if(index + 2 < s.length())        {            string str = s.substr(index, 3);            int n;            stringstream ss;            ss << str;            ss >> n;            if(n >= 100 && n <= 255) dfs(res, s, depth + 1, ip + "." + str, index + 3);        }    }    vector<string> restoreIpAddresses(string s) {        vector<string> res;        if(s.length() > 12) return res;        dfs(res, s, 0, "", 0);        return res;    }};


0 0