93. Restore IP Addresses
2015-08-06 19:19
543 查看
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given
return
分析:按照dfs的方式递归的计算,具体见代码注释。需要注意的一点是,为了加快dfs的回溯速度,应该尽可能对dfs过程进行剪枝。
For example:
Given
"25525511135",
return
["255.255.11.135", "255.255.111.35"]. (Order does not matter)
分析:按照dfs的方式递归的计算,具体见代码注释。需要注意的一点是,为了加快dfs的回溯速度,应该尽可能对dfs过程进行剪枝。
class Solution { public: vector<string> restoreIpAddresses(string s) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<string> res; string tmpres; restoreIpAddressesRecur(s, 0, 4, tmpres, res); return res; } //从s的start位置开始计算,ip地址还需要num个域(共4个域) //tmpres表示当前计算好的部分ip void restoreIpAddressesRecur(string &s, int start, int num, string &tmpres, vector<string> &res) { int len = s.size(); if(num == 0) { if(start == len)//已经计算好了一个ip { tmpres.erase(--tmpres.end());//去掉最后的“.” res.push_back(tmpres); tmpres.push_back('.'); } return; } //不满足最小或最大长度关系 if(len - start < num || len - start > num*3)return; int tmplen = tmpres.size(); string tmpstr; for(int i = 1; i <= 3 && start + i <= len; i++) {//ip地址的一个域最多包含三个数字 if(validRegion(s, start, start+i-1) == false)continue; tmpstr = s.substr(start, i) + "."; tmpres += tmpstr; restoreIpAddressesRecur(s, start+i, num-1, tmpres, res); tmpres.erase(tmplen, i+1); } } //判断ip地址的一个域是否合法 bool validRegion(string &s, int istart, int iend) { if(iend > istart && s[istart] == '0')return false; int res = 0; for(int i = istart; i <= iend; i++) res = res*10 + (s[i] - '0'); if(res >= 0 && res <= 255)return true; else return false; } };
相关文章推荐
- 七把利器助你打造充满竞争力的商业模式
- 组合数学之母函数问题
- datawindow.net 动态按条件汇总字段值
- 如何长时间高效学习?
- Memcached中item锁的粒度
- Box2D C++教程-设置世界(World)7
- java 集合框架--14
- 锁定客户的六大策略:教你如何将切换成本嵌入商业模式
- centos网络设置
- LeetCode 239 Sliding Window Maximum
- Android onconfiguration属性
- hdu 3336 Count the string(kmp应用)
- c++类实现基本的6种排序算法
- hdu 4750——Count The Pairs
- Android 圆形滚动菜单
- —软测试—(5)计算机系统CPU组成
- Nginx: could not build the server_names_hash 解决办法
- poj3301--Texas Trip(最小正方形覆盖)
- MySQL IN用法
- 【费用流】 HDOJ 5352 MZL's City