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)
主要思想:采用遞歸的方式,一個一個的加入到最後的ip中
void formIpAddr(vector&ret, string curIp, string nums, int idxIp){ if(idxIp==1){ if(nums.size()>3 || (nums.size()>1&&nums[0]=='0')){ return ; } const char * data=nums.c_str(); if(nums.size()<=2||atoi(data)<=255){ ret.push_back(curIp+nums); return; } } else{ if(nums[0]=='0'){ string tmp=curIp+nums.substr(0,1)+.; formIpAddr(ret, tmp, nums.substr(1), idxIp-1); return; } else{ int i; string tmp; for(i=0; i<2 && i+idxIp<=nums.size(); i++){ tmp=nums.substr(0, i+1); formIpAddr(ret, curIp+tmp+., nums.substr(i+1), idxIp-1); } if(i+idxIp<=nums.size()){ const char * data=nums.substr(0,i+1).c_str(); tmp=nums.substr(0, i+1); if(atoi(data)<=255) formIpAddr(ret, curIp+tmp+., nums.substr(i+1), idxIp-1); } } } } vector restoreIpAddresses(string s) { vector ret; if(s.size()<4) return ret; string curIp=; formIpAddr(ret, curIp, s, 4); return ret; }