Question:
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地址是否合法,每一段都要小于等于255,一共四段
Algorithm:
DFS,要注意当前元素为0时,0为一段,继续DFS,00是非法的。
Accepted Code:
class Solution { public: vector<string> res; vector<string> restoreIpAddresses(string s) { DFS(res,s,"",0,0); return res; } void DFS(vector<string>& res,string s,string t,int count,int k) //count表示段数,k表示s遍历的位置 { if(count==4&&k==s.size()) { res.push_back(t); return; } else if(count>3) return; string tmp1=t; if(s[k]=='0') //当前元素为0时,即为一段 { tmp1.push_back(s[k]); if(count!=3) tmp1.push_back('.'); DFS(res,s,tmp1,count+1,k+1); } else { int sum=0; for(int i=k;i<s.size();i++) { sum=sum*10+(s[i]-'0'); if(sum<=255) { string tmp2=tmp1; //tmp1为未打点,tmp2已打点成为一段 tmp2.push_back(s[i]); tmp1.push_back(s[i]); if(count!=3) //第四段即count==3时,尾部不打点 tmp2.push_back('.'); DFS(res,s,tmp2,count+1,i+1); } else break; } } } };
时间: 2024-10-29 00:22:57