C++ recursive solution


  • 0
    J
    vector<string> restoreIpAddresses(string s) {
        vector<string> ips;
        getIPs(ips, "", s, 0);
        return ips;
    }
    
    void getIPs(vector<string>& ips, string ip, string s, int digit) {
        if(s == "" && digit != 4 || s != "" && digit == 4)
            return;
        
        if(s == "" && digit == 4) {
            ip.pop_back();
            ips.push_back(ip);
            return;
        }
    
        getIPs(ips, ip + s.substr(0, 1) + ".", s.substr(1), digit + 1);
        
        if(s.length() >= 2 && s[0] != '0') {
            string num = s.substr(0, 2);
            if(stoi(num) > 0 && stoi(num) <= 255)
                getIPs(ips, ip + s.substr(0, 2) + ".", s.substr(2), digit + 1);
        }
        
        if(s.length() >= 3 && s[0] != '0') {
            string num = s.substr(0, 3);
            if(stoi(num) > 0 && stoi(num) <= 255)
                getIPs(ips, ip + s.substr(0, 3) + ".", s.substr(3), digit + 1);
        }
    }

Log in to reply
 

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