[leetcode]Restore IP Addresses
链接:https://leetcode.com/problems/restore-ip-addresses/description/
Question
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example 1
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
Solution
class Solution {
public:
vector<string> res;
string s;
void dfs(int left, vector<int> ans) {
if (ans.size() == 3) {
if (s.size()-left >= 4) return;
string sub = s.substr(left, s.size()-left);
if (s[left] == '0' && sub.size() > 1) return;
int temp = stoi(sub.c_str());
string str;
if (temp > 255) return;
ans.push_back(temp);
for (int i = 0; i < 4; i++)
if (i != 3) str += to_string(ans[i])+".";
else str += to_string(ans[i]);
res.push_back(str);
return;
}
for (int gap = 1; gap <= 3; gap++) {
if (left + gap < s.size()) {
string sub = s.substr(left, gap);
// 去除没有意义的情况
if (s[left] == '0' && gap > 1) break;
int num = stoi(sub.c_str());
if (num <= 255) {
ans.push_back(num);
dfs(left+gap, ans);
ans.pop_back();
} else {
break;
}
} else {
break;
}
}
}
vector<string> restoreIpAddresses(string s) {
if (s.size() > 12 || s.size() < 4) return vector<string>();
this->s = s;
this->res.clear();
dfs(0, vector<int>());
return res;
}
};
思路:回溯递归常规题:-)