Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
一般遇到求所有可能结果的题目,首先考虑的是递归方法
class Solution {
public:
void restore(string s, int k, string pre, vector<string>& res){
if (s.size()<k || s.size()>3*k) {
return;
}
if (k ==0){
res.push_back(pre);
}
for (int i = 1; i<=3; i++){
if (s.size() >= i && isValid(s.substr(0, i))){
if (k==1){
restore(s.substr(i), k-1, pre+s.substr(0,i), res);
}else{
restore(s.substr(i), k-1, pre+s.substr(0,i) + ".", res);
}
}
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> res;
restore(s, 4, "", res);
return res;
}
bool isValid(string s) {
if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) return false;
int res = atoi(s.c_str());
return res <= 255 && res >= 0;
}
};
网友评论