var restoreIpAddresses = function(s) {
let answers = [];
let answer = [];
function backtrack(index, start){
if(index == 4)//走到最后一层
if(start == s.length){//走到了最后一个字符
answers.push(answer.join('.'));
return;
}
else
return;
let i = start;
//将一个字符放入解
if(i < s.length){
answer.push(s[i]);
backtrack(index + 1, i + 1);
answer.pop();
}
//将两个字符放入解
if(i + 1 < s.length && Number(s[i] + s[i + 1]) >= 10){
answer.push(s[i] + s[i + 1]);
backtrack(index + 1, i + 2);
answer.pop();
}
//将三个字符放入解
if(i + 2 < s.length && Number(s[i] + s[i + 1] + s[i + 2]) >= 100 &&Number(s[i] + s[i + 1] + s[i + 2]) <= 255){
answer.push(s[i] + s[i + 1] + s[i + 2]);
backtrack(index + 1, i + 3);
answer.pop();
}
}
backtrack(0,0);
return answers;
};
|