标签:
Title:
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)
思路:使用DFS进行深度搜索。对于每个index处,考虑index~index+2,因为ip地址最多是3位整数。同时需要注意剪枝。另外根据提交,应该是不支持01.001这样的IP地址,所以需要排除
class Solution{ public: vector<string> restoreIpAddresses(string s) { vector<string> results; string ip; dfs(0,4,s,ip,results); return results; } void dfs(int index, int num,string s,string ip, vector<string> & results){ if (index == s.size() && num == 0){ results.push_back(ip); return ; } if (s.size() - index < num || s.size() - index > 3 * num) //剪枝 return ; int sum = 0; for (int i = index; i < index+3; i++){ if (i < s.size()){ sum = sum * 10 + s[i]-‘0‘; if (sum <= 255){ ip += s[i]; if (num > 1) dfs(i+1,num-1,s,ip+‘.‘,results); else dfs(i+1,num-1,s,ip,results); } if (sum == 0)//可以是0,但是首位是0之后,后面的就不能再用 break; } } } };
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4485075.html