Wednesday, December 10, 2014

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)

I know it's backtracking, but this problem is harder than I had thought to code it right and I don't quite understand the second solution.

Answer 1:
class Solution {
public:
    bool valid(string s)
    {
        int n=s.size();
        int v = atoi(s.c_str());
        if (n==3&(v==0||v>255)) return false;
        if (n==2&&(v==0||s[0]=='0')) return false;
        if (n==3&&(s[0]=='0')) return false;
        return true;
    }
    void  dfs(vector<string> &res, string s, string ip, int k)
    {
        if (k==0)
        {
            if (s.empty())
            {
                res.push_back(ip);
            }
            return;
        }
        else
        {
            for (int i=1; i<=3; i++)
            {
                if (s.size()>=i&&valid(s.substr(0,i)))
                {
                    if (k==1)
                       dfs(res,s.substr(i),ip+s.substr(0,i),k-1);
                    else
                       dfs(res,s.substr(i),ip+s.substr(0,i)+".", k-1);
                }
            }
           
        }
    }
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        dfs(res,s,"",4);
        return res;
    }
};


Answer2 :

class Solution {
public:
 void dfs(string s, int start, int step, string ip, vector<string>& result)
 {
     int n=s.size();
     if (start==n &&step==4)
     {
         ip.erase(ip.size()-1);
         result.push_back(ip);
         return;
     }
    
     if (n-start>(4-step)*3)
         return;
     if (n-start<4-step)
         return;

        
     int num=0;
    
     for (int i=start; i<start+3&&i<n; i++)
     {
         num=num*10+(s[i]-'0');
        
         if (num<=255){
             ip+=s[i];
             dfs(s,i+1,step+1,ip+'.', result);
         }
         if (num==0) break;

     }
    
    }
 vector<string> restoreIpAddresses(string s) {
     vector<string> result;
     string ip;
    
     dfs(s,0,0,ip,result);
     return result;
 }
};

No comments:

Post a Comment