您的位置:首页 > 其它

Restore IP Addresses

2015-04-13 05:34 176 查看
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)

貌似刚csdn抽风了, 回溯法, 找四个符合条件的数字组成一个ip, 注意三个问题:

1. 符合条件的数字: 1-3位, 0-255之间,且不能010出现

2. 停止条件, 有四个数字,且无剩余数字

3. 回溯, push, next, pop...

class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
vector<string> solution;
scanIp(s,0,res,solution);
return res;
}

private:
bool isValid(const string& s){
int n=s.size();
if (n==0 || n>3)
return false;
if (s[0]=='0' && n>1)
return false;
if (n==3 && atoi(s.c_str())>255)
return false;
return true;
}

void scanIp(const string& s, int index, vector<string>& res, vector<string>& solution){
if (solution.size()==4){ // stopping condition, have 4 numbers
if (index==s.size()){ // there is not left numbers, otherwise, invalid
string tmp=solution[0];
for (int i=1; i<4; i++)
tmp=tmp+"."+solution[i];
res.push_back(tmp);
}
return;
}

string num;
for (int i=index; i<s.size()&& i<index+3; i++){
num.push_back(s[i]);
if (isValid(num)){
solution.push_back(num);
scanIp(s,i+1, res, solution);
solution.pop_back();
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode