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的规则!
class Solution { public: vector<string> restoreIpAddresses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<string> *v = new vector<string>(); int * array = new int[4]; DepthFirst(0,s.length()-1,0,array,s,v); return *v; } void DepthFirst(int l,int r,int depth,int *array,string source,vector<string> *v) { if(depth == 4) { int l0 = 0,l1 = array[0],l2 = array[1]+array[0],l3 = array[2] + array[1] + array[0]; string s = source.substr(l0,array[0]) + "." + source.substr(l1,array[1]) + "." + source.substr(l2,array[2]) + "." + source.substr(l3,array[3]); v->push_back(s); return; } for(int i = 1;i <= 3;i++) { if(r - l - i + 1 < 3 - depth) continue; if(r - l - i + 1 > 3 * (3 - depth)) continue; if(i > 1) { if(source.at(l) == '0') continue; } int num = 0; int pow[3] = {1,10,100}; for(int j = i; j >= 1; j--) { num += (source.at(l + j - 1) - '0')*pow[i - j]; } if(num > 255) continue; array[depth] = i; DepthFirst(l+i,r,depth+1,array,source,v); } } };

浙公网安备 33010602011771号