leetcode7 recover IP address

Title:

First of all, fat bloggers need to note that the length of IP address string is less than 12, and every three bits must not be greater than 255...

Code reference https://www.cnblogs.com/ariel-dreamland/p/9159611.html

If k = 0, three points have been added and four segments have been formed. If the string is empty at this time, the currently divided result will be saved. If K! = 0, for each segment, we use one bit, two bits and three bits respectively to try to determine whether it is legal. If it is legal, we call recursion to continue to divide the remaining strings, and finally sum up to find all the legal combinations.

bool isValid(string s) {
       if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) return false;
       int res = atoi(s.c_str());
       return res <= 255 && res >= 0;
   }
void restore(string&s,int k,string out,vector<string>&res)
{
	if (k==0)
	{
		if (s.empty())
		{
			res.push_back(out);
		}
	}
	else
	{
		for (int i = 1; i <= 3; ++i) 
		{
	         if (s.size() >= i && isValid(s.substr(0, i))) 
			 {
			        if (k == 1) restore(s.substr(i),k-1, out + s.substr(0, i), res);
			        else restore(s.substr(i), k - 1, out + s.substr(0, i) + ".", res);
			 }
	    }

	}
}

vector<string> restoreIpAddresses(string s) 
{
	vector<string>res;
	//Size first
	if (s.size()>12)
	{
		return res;
	}
	restore(s,4,"",res);
	return res;
}

Or simplify it a little bit

Omit isValid function, and use if statement to filter out inconformity before calling recursion. In fact, K! = STD:: to_string (VAL). Size() is not difficult to understand. For example, when k=3, it means that it should be a three digit number, but if the character is "010", then the integer type val=10, and then the return string is "10". At this time, the length and K value are different, so you can In order to find out the unsatisfactory situation.

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        helper(s, 0, "", res);
        return res;
    }
    void helper(string s, int n, string out, vector<string>& res) {
        if (n == 4) {
            if (s.empty()) res.push_back(out);
        } else {
            for (int k = 1; k < 4; ++k) {
                if (s.size() < k) break;
                int val = atoi(s.substr(0, k).c_str());
                if (val > 255 || k != std::to_string(val).size()) continue;
                helper(s.substr(k), n + 1, out + s.substr(0, k) + (n == 3 ? "" : "."), res);
            }
        }
    }
};

 

Keywords: less

Added by Locked on Tue, 31 Dec 2019 10:47:34 +0200