93. Restore IP Addresses

93. Restore IP Addresses

topic

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)

Parse

  • Triple loop, traverse the position of three decimal points, and check each position: [LeetCode] 93. Restore IP Addresses]( https://www.cnblogs.com/ganganloveu/p/3780607.html )

  • Recursive, ip addresses are divided into 4 groups, and the validity of each group is checked.

class Solution_93 {
public:
    bool isValid(string str)
    {
        long temp = atol(str.c_str()); //用int溢出;atol
        if (temp>255)
        {
            return false;
        }
        if (str[0]=='0'&&str.size()>1)
        {
            return false;
        }
        return true;
    }
    void dfs(vector<string> &res, string t, string s, int cnt)
    {
        if (cnt>3)
        {
            return;
        }
        if (cnt==3&&isValid(s)) //最后一组数
        {
            res.push_back(t+s);
            return;
        }
        for (int i = 1; i < 4 && i < s.size();i++)
        {
            string sub = s.substr(0, i);
            if (isValid(sub))
            {
                dfs(res, t + sub + '.', s.substr(i), cnt + 1);
            }
        }
        return;
    }

    vector<string> restoreIpAddresses(string s) {

        vector<string> res;
        string t;
        dfs(res,t,s,0);
        return res;
    }
};

topic source

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324404195&siteId=291194637