93. Restore IP Addresses

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_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;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8835497.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞