93. Restore IP Addresses



Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

 

class Solution {
public:
    vector<vector<string>> res;
    void backtrack(string&s ,vector<string> &path, int start) {
        if (path.size() == 4 && start == s.length()) {
            res.push_back(path);
            return;
        }
        for(int i = start; i < s.length();++i) {
            //[start, i]
            if (is_valid(s, start, i)) {
                path.push_back(s.substr(start,i-start+1));
                backtrack(s,path,i+1);
                path.pop_back();
            } else {
                break;
            }
        }
    }
    //
    bool is_valid(string &s,int start, int index) {

        if (s[start]=='0' && start != index) {
            return false;
        }
        if( start > index) {
            return false;
        }
        if (stoi(s.substr(start,index-start+1))>255) {
            return false;
        }
        return true;
    }
    vector<string> restoreIpAddresses(string s) {
        vector<string> final_res;
        if (s.length() > 12) {
            return final_res;
        }
        vector<string> path;
        backtrack(s,path,0);

        for (auto s_vec : res) {
            string ip = "";
            for (auto c:s_vec) {
                ip+=(c+'.');
            }
            final_res.push_back(ip.substr(0,ip.length() -1));
        }
        return final_res;
    }
};

 

 

 

 1     // c++  code
 2     vector<string> restoreIpAddresses(string s) {
 3         vector<string> ret;
 4         string ans;
 5         
 6         for (int a=1; a<=3; a++)
 7         for (int b=1; b<=3; b++)
 8         for (int c=1; c<=3; c++)
 9         for (int d=1; d<=3; d++)
10             if (a+b+c+d == s.length()) {
11                 int A = stoi(s.substr(0, a));
12                 int B = stoi(s.substr(a, b));
13                 int C = stoi(s.substr(a+b, c));
14                 int D = stoi(s.substr(a+b+c, d));
15                 if (A<=255 && B<=255 && C<=255 && D<=255)
16                     if ( (ans=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D)).length() == s.length()+3)
17                         ret.push_back(ans);
18             }    
19         
20         return ret;
21     }

 

posted @ 2019-01-10 22:49  乐乐章  阅读(137)  评论(0编辑  收藏  举报