C++ solution for Restore IP Addresses


  • 0
    S

    class Solution {
    public:

    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        string s_sub="";
        restore(res, 0, s, s_sub,0);
        return res;
    }
    
    void restore(vector<string> &res, int start, string s, string s_sub, int part){
        if (s=="") return;
        if(start==s.size() && part==4) {
            s_sub.pop_back();
            res.push_back(s_sub);
            return;
        }
      
        int count=0;
        if(s.size() - start > (4-part)*3) return;   
        if(s.size() - start < (4-part)) return; 
        if (part>4) return;
        
        for (int i=start; i<start+3 && i<s.size() ;i++){
                count=count*10+(s[i]-'0');
                
                if (count<=255 && count>0) {
                    s_sub=s_sub+s[i];
                    restore(res, i+1, s, s_sub+".", part+1);
                }
                if(count==0) {
                    s_sub=s_sub+s[i];
                    restore(res, i+1, s, s_sub+".", part+1);
                    break;                   
                }             
        }
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.