美文网首页
Restore IP Addresses

Restore IP Addresses

作者: joey_zhou | 来源:发表于2019-08-21 23:33 被阅读0次

    Restore IP Addresses

    Given a string containing only digits, restore it by returning all possible valid IP address combinations.

    一般遇到求所有可能结果的题目,首先考虑的是递归方法

    class Solution {
    public:
    
        void restore(string s, int k, string pre, vector<string>& res){
            if (s.size()<k || s.size()>3*k) {
                return;
            }
            if (k ==0){
                res.push_back(pre);
            }
            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, pre+s.substr(0,i), res);
                    }else{
                        restore(s.substr(i), k-1, pre+s.substr(0,i) + ".", res);
                    }
                }
            }
        }
        vector<string> restoreIpAddresses(string s) {
            vector<string> res;
            restore(s, 4, "", res);
            return res;
        }
    
        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;
        }
    };
    

    相关文章

      网友评论

          本文标题:Restore IP Addresses

          本文链接:https://www.haomeiwen.com/subject/ceowsctx.html