标签:
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)
深度优先遍历的思想,类似的题目还有:
4.Letter Combinations of a Phone Number
class Solution { public: int strToInt(string &str) { int res = 0; for(int i=0;i<str.size();i++){ res = res*10+(str[i]-‘0‘); } return res; } void dfs(string& s,int sSize,int startPos,vector<string>& res,string oneOfRes,int k) { for(int i=startPos;(i<sSize) && (i<startPos+3) ;i++){ if(i!=startPos && s[startPos]==‘0‘){ return; } string tmpStr = s.substr(startPos,i-startPos+1); int value = strToInt(tmpStr); if(value>255){ return; } string tmpOneOfRes = oneOfRes; oneOfRes.empty()? oneOfRes += tmpStr : oneOfRes += "."+tmpStr; if(k+1<4){ dfs(s,sSize,i+1,res,oneOfRes,k+1); }else{ if(i+1==sSize){ if(find(res.begin(),res.end(),oneOfRes)==res.end()) res.push_back(oneOfRes); } } oneOfRes = tmpOneOfRes; } } vector<string> restoreIpAddresses(string s) { vector<string> res; string oneOfRes ; dfs(s,s.size(),0,res,oneOfRes,0); return res; } };
标签:
原文地址:http://www.cnblogs.com/zengzy/p/5024558.html