Restore IP Addresses

Posted xpp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Restore IP Addresses相关的知识,希望对你有一定的参考价值。

方法:采用递归的方式

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> result;
        restore(s, 4, "", result);
        return result;
    }
    
private:
    void restore(string s, int k, string path, vector<string> &result)
    {
        if(k == 0)
        {
            if(s.empty())
                result.push_back(path);
        }
        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, path + s.substr(0, i), result);
                    else
                        restore(s.substr(i), k-1, path + s.substr(0, i) + ".", result);
                }
            }
        }
    }
    
    bool isValid(string s)
    {
        if(s.size() > 3 || s.empty() || (s.size() > 1 && s[0] == 0))
            return false;
            
        int num = stoi(s);
        return num >= 0 && num <= 255;
    }
};

 

以上是关于Restore IP Addresses的主要内容,如果未能解决你的问题,请参考以下文章

93. Restore IP Addresses

Restore IP Addresses

93. Restore IP Addresses

93. Restore IP Addresses

leetcode - Restore IP Addresses

93. Restore IP Addresses