题目:https://leetcode-cn.com/problems/restore-ip-addresses/ 参考:https://leetcode-cn.com/problems/restore-ip-addresses/solution/cdi-gui-hui-su-jian-zhi-by-codave/
class Solution {
public:
vector restoreIpAddresses(string s) {
/*
*stoi与to_string的应用
*/
this->s = s;
len = s.length();
dfs(0,"",0);
return ans;
}
void dfs(int pos,string ip,int cur) {
if(pos >= 4) {
if(cur >= len)
ans.push_back(ip);
return;
}
for(int k = 1;k len) break;
int val = stoi(s.substr(cur,k));
if(val > 255 || k != (int)to_string(val).size()) continue;
dfs(pos+1,ip + s.substr(cur,k)+(pos == 3 ? "":"."),cur+k);
}
}
private:
vector ans;
int len;
string s;
};