class Solution {
public:vector<string> strs;//用于存放臨時的四個段vector<string> result;//存放結果void dfs(string &s, int beginIndex, int step) {if (step == 4 && beginIndex == s.size()) //搜索成功{string temRec = strs[0] + "." + strs[1] + "." + strs[2] + "." + strs[3];result.push_back(temRec);}else if (step < 4) //當還需要搜索{for (int len = 1; len < 4; ++len) //對這個段的長度進行窮舉{if (beginIndex + len <= s.size()) //判斷下標的合法性{strs[step] = s.substr(beginIndex, len);//獲取這個段//檢測strs[step]這個段的合法性//是否是“023”長度大于1且首位位0這種 或者“345”這種超過防偽if ((strs[step][0] == '0' && strs[step].size() > 1) || stoi(strs[step]) > 255) {continue;}dfs(s, beginIndex + len, step + 1);//進行下一步搜索}}}}vector<string> restoreIpAddresses(string s) {strs = vector<string>(4);dfs(s, 0, 0);//開始搜索return result;}
};
?