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"] 解题思路: IP每一段的数字范围是:0~255,不可以超过此范围,而且第一段不能为0,可以使用DFS进行搜索, 深度满足4时,进行返回.
GO语言实现
package main
import (
"fmt"
"strconv"
)
func restoreIPAddresses(s string)[]string{
res,ip:=make([]string,0),make([]int,0)
if len(s)<4||len(s)>12{
res=append(res,s)
return res
}
DFS(s,0,ip,&res)
return res
}
func DFS(s string,index int,ip []int,res *[]string){
if index==len(s){
if len(ip)==4{
*res=append(*res,getstring(ip))
}
return
}
if index==0{
num,_:=strconv.Atoi(string(s[0]))
ip=append(ip,num)
DFS(s,index+1,ip,res)
}else{
num,_:=strconv.Atoi(string(s[index]))
next:=ip[len(ip)-1]*10+num
if next<=255&&ip[len(ip)-1]!=0{
fmt.Println(ip)
ip[len(ip)-1]=next
DFS(s,index+1,ip,res)
ip[len(ip)-1]/=10
}
if len(ip)<4{
ip=append(ip,num)
DFS(s,index+1,ip,res)
ip=ip[:len(ip)-1]
}
}
}
func getstring(ip []int)string{
res:=strconv.Itoa(ip[0])
for i:=1;i<len(ip);i++{
res+="."+strconv.Itoa(ip[i])
}
return res
}
C++语言实现
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution{
private:
vector<string> ans;
string s;
int n;
public:
vector<string> restoreIPAddress(string& _s){
if(_s.size()<4||_s.size()>12)
return ans;
s=_s;
n=_s.size();
dfs(0,0,"");
return ans;
}
private:
void dfs(int index,int depth,string path){
if(depth==4){
path.pop_back();
ans.push_back(path);
return;
}
int Min=max(index+1,n-(3-depth)*3);
int Max=min(index+3,n-(3-depth));
for(auto i=Min;i<=Max;i++){
string split=s.substr(index,i-index);
auto len=split.size();
if(len>1&&split[0]=='0')
break;
if(stoi(split)<=255){
dfs(i,depth+1,path+(split+'.'));
}
}
}
};
int main(int argc,char* argv[]){
string s="22522511135";
vector<string> ans=Solution().restoreIPAddress(s);
for(auto& i:ans)
cout<<i<<endl;
return 0;
}