93. Restore IP Addresses
来源: LeetCode 93. Restore IP Addresses
题目描述
93. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.
思路分析
IPV4复原3个一组双指针
利用回溯法
parament : pos, rmind, path // 位置,可支配, 路径
代码
class Solution {
#define SIZE(A) ((int)A.size())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()
using VI = vector<int>;
using VII = vector<VI>;
using VD = vector<double>;
typedef pair<int, int> PI;
public:
string _s;
vector<string> res;
vector<string> restoreIpAddresses(string s) {
_s = s;
vector<string> temp;
dfsBactrack(0, temp);
return res;
}
void dfsBactrack(int pos, vector<string>& path){
if(SIZE(_s) - pos > (4 - SIZE(path))*3) return;// 剩下的元素超标
if(pos == SIZE(_s) && SIZE(path) == 4){
string ans;
REP(i,3){
ans += path[i];
ans += ".";
}
res.PB(ans + path.back());
return;
} // 合格路径
string ip;
int end = min(SIZE(_s), 3+pos);
FOR(i, pos, end){
ip += _s[i];
if(!isValid(ip)) continue;
path.PB(ip); // 做出选择
dfsBactrack(i+1, path);
path.pop_back(); // 撤销选择
}
}
bool isValid(string s){
if(s[0] == '0')
return s.size() == 1;
return stoi(s) < 256;
} // 判断是否为数字
};