leetcode :Restore IP Addresses
这一题是深搜问题
考虑问题:
1、IP地址位数不够,如string = "123";
2、IP地址位数太长,如string = "255255255255222";
3、如果出现连0的情况,只能取其中一个0,如果00.1.1.1是不合法的
代码:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> result;
string ip;
Solution::getIpAddresses(s, 0, 1, ip, result);
return result;
}
void getIpAddresses(string s, int start, int count, string ip, vector<string> &result){
int sLen = s.length();
if (start == sLen && count == 5){
ip.pop_back();
result.push_back(ip);
return;
}
if (sLen - start - 3 > 12 - 3 * count || sLen - start < 4 - count)
return;
int num = 0;
for (int i = start; i < start + 3 && i < s.length(); i++){
num = num * 10 + s[i] - '0';
if (num < 256){
ip = ip + s[i];
getIpAddresses(s, i + 1, count + 1, ip + '.', result);
}
if (num == 0) break;
}
}
};