Restore IP Addresses
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)
Solution: DFS.
1 class Solution { 2 public: 3 vector<string> restoreIpAddresses(string s) { 4 vector<string> res; 5 string ip; 6 restoreIpAddressRe(s, res, ip, 0, 0); 7 return res; 8 } 9 10 void restoreIpAddressRe(string &s, vector<string> &res, string &ip, int deep, int start) 11 { 12 if (deep == 4 && start == s.size()) 13 res.push_back(ip); 14 if (deep == 4) return; 15 16 int num = 0, origSize = ip.size(); 17 if (origSize != 0) ip.push_back('.'); 18 for (int i = start; i < s.size(); ++i) 19 { 20 num = num * 10 + s[i] - '0'; 21 if (num > 255) break; 22 ip.push_back(s[i]); 23 restoreIpAddressRe(s, res, ip, deep + 1, i + 1); 24 if (num == 0) break; 25 } 26 ip.resize(origSize); 27 } 28 };