首页 > 代码库 > Restore IP Addresses

Restore IP Addresses

Restore IP Addresses

 Total Accepted: 12696 Total Submissions: 61955My Submissions

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)

Have you been asked this question in an interview? 

此题是比较基础的搜索题,要找出所有的可行解,直接用DFS即可。

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        ans.clear();
        store(s, 0, "");
        return ans;
    }
private:
    vector<string> ans;
    void store(const string& s, int b, string ip) {
        for (int i = b; i < s.size(); ++i) {
            string sub_str = s.substr(b, i - b + 1);
            if (isValidIp(sub_str)) {
                if (i + 1 == s.size() && count(ip.begin(), ip.end(), '.') == 2) {
                    ans.push_back(ip + "." + sub_str);
                } else {
                    string temp_ip = ip;
                    if (temp_ip == "") {
                        temp_ip += sub_str;
                    } else {
                        temp_ip += "." + sub_str;
                    }
                    if (count(ip.begin(), ip.end(), '.') ==3) {
                        continue;
                    }
                    store(s, i + 1, temp_ip);
                }
            }
        }
    }
    bool isValidIp(const string& s) {
        if (s.size() > 3) {
            return false;
        }
        if (s.size() == 3 && s > "255") {
            return false;
        }
        if (s.size() > 1 && s[0] == '0') {
            return false;
        }
        return true;
    }
};


Restore IP Addresses