resotreIpAddress
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)
Subscribe to see which companies asked this question
1 #include <string> 2 #include <vector> 3 using namespace std; 4 class Solution { 5 public: 6 vector<string> restoreIpAddresses(string s) { 7 vector<string> result; 8 vector<int> path; 9 dfs(s,0,0,path,result); 10 return result; 11 } 12 private: 13 void dfs(string& s,int start,int num, 14 vector<int>& path,vector<string>& result){ 15 if(num == 3) { 16 string str = s; 17 for(int i=0;i<3;i++){ 18 str.insert(path[i]+i,1,'.'); 19 } 20 result.push_back(str); 21 return; 22 } 23 24 for(int i=1;i<4;i++){ 25 if((start+i)<s.length() && 3-num<=s.substr(start+i).length() && s.substr(start+i).length()<=(3-num)*3){ 26 if(stoi(s.substr(start,i))<=255){ 27 if(i>1 && s[start] =='0') break; 28 if(num==2 && stoi(s.substr(start+i))>255) continue; 29 if(num==2 && s.substr(start+i).length()>1 && s[start+i]=='0') continue; 30 31 if(path.empty()) path.push_back(i); 32 else path.push_back(path.back()+i); 33 dfs(s,start+i,num+1,path,result); 34 path.pop_back(); 35 } 36 } 37 } 38 } 39 }; 40 int main(){ 41 string IPaddress="1203045"; 42 Solution s; 43 vector<string> result; 44 result = s.restoreIpAddresses(IPaddress); 45 return 0; 46 }