Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
典型的深搜问题:
#include <iostream> #include<vector> #include <string> using namespace std; bool isValid(string s, int start, int end) { if (s[start]=='0') //不能以0开头 { return false; } if (end-start>3) //防止num超出int范围溢出 { return false; } int num = 0; for (int i=start;i<=end;i++) { num = num*10 + s[i]-'0'; } if (num<=255) //判断数字是否有效 { return true; } return false; } void DFS(string s, int curPos, int curStep, string& curIP, vector<string>& result) { if (s.size()-curPos > (5-curStep)*3) //防止出现多于四个字段的情况 如:2.5.5.2.2.5 { return; } if (curPos == s.size()) { curIP.erase(curIP.end()-1); //把最后一个字段多加的‘.’弹出 result.push_back(curIP); return ; } for (int i=curPos;i<s.size();++i) { if (isValid(s,curPos,i)) { curIP.insert(curIP.begin()+i+curStep, '.'); //压栈 DFS(s,i+1,curStep+1,curIP,result); curIP.erase(curIP.begin()+i+curStep); //出栈 } } } int main() { string s="25525511035"; string curIP =s; vector<string> result; DFS(s,0,1,curIP,result); return 0; }