93.Restore IP Addresses

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 {
public:
    vector restoreIpAddresses(string s) {
        vector ret;
        if(s.size() > 12)
            return ret;
        for(int i = 0; i < s.size(); i ++)
        {// [0, i]
            for(int j = i+1; j < s.size(); j ++)
            {// [i+1, j]
                for(int k = j+1; k < s.size()-1; k ++)
                {// [j+1, k], [k+1, s.size()-1]
                    string ip1 = s.substr(0, i+1);
                    string ip2 = s.substr(i+1, j-i);
                    string ip3 = s.substr(j+1, k-j);
                    string ip4 = s.substr(k+1);
                    if(check(ip1) && check(ip2) && check(ip3) && check(ip4))
                    {
                        string ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
                        ret.push_back(ip);
                    }
                }
            }
        }
        return ret;
    }
    bool check(string ip)
    {
        int value = stoi(ip);
        if(ip[0] == '0')
        {
            return (ip.size() == 1);
        }
        else
        {
            if(value <= 255)
                return true;
            else
                return false;
        }
    }
};


你可能感兴趣的:(回溯,string,leetcode)