DFS所有可能。。。
class Solution { public: void search(const string& s , vector<string>& ans , int step , const string& ip , int start){ if(s.size() == start && step == 4){ ans.push_back(ip.substr(1 , ip.size()-1)); // cout << ip.substr(1 , ip.size()-1) <<endl; } if(s.size() <= start) { return; } //enumation //length 1,2,3 //1 // cout << step << " "<< ip << endl; if(start < s.size()) { // cout << "get in" <<endl; string tip = s.substr(start,1); // cout<< tip << endl; search(s , ans , step + 1 , ip + "." + tip , start + 1); } //2 if(start + 1 < s.size()){ string tip = s.substr(start,2); if(tip[0] != '0') search(s , ans , step + 1 , ip + "." + tip , start + 2); } //3 if(start + 2 < s.size()){ string tip = s.substr(start,3); stringstream ss; ss << tip; int n; ss >> n; if(n>=100 && n <= 255) search(s , ans , step + 1 , ip + "." + tip , start + 3); } } vector<string> restoreIpAddresses(string s) { vector<string> ans; if(s.size() > 3*4) return ans; search(s , ans , 0 , "" , 0); return ans; } };