IP地址,分成四段,每段是0-255,按照每段的长度分别为1,2,3下一段长度分别1,2,3再下一段。。。。。。进行递归遍历,能满足条件的假如res中。比较难想到的就是假如有一段是三位的010是不符合要求的。这点一开始没想到,改成首尾不是0的才执行结果又漏掉了单个0的IP地址,比如0.0.0.0.。除了这两点之外剩下的代码还算好想。

#include<bits/stdc++.h>
using namespace std;
class Solution {
private:
void getIP(string s,int x,int y,vector<string>&res,string &ans,int sum)//[x,x+y-1]前闭后闭从string s的第x位开始获取y位数字组成IP地址。
{
int n;
n = s.size();
int i;
if (x + y -> n - ||sum>)
return;
if (( - sum) * + x + y- < n - )//如果剩下的几次都取3个数字都取不完所有元素,那么返回。
return;
if (y == )
{
if ( * (s[x] - '') + * (s[x + ] - '') + (s[x + ] - '') > )
return;
}
if (s[x] - '' == &&y!=)
return;
for (i = x; i <= x + y-; i++)
{
ans.push_back(s[i]);
if (i == x + y-&&sum!=)
ans.push_back('.');
}
if (x + y- == n - &&sum==)//第三次取完了所有string s里面的元素,保存结果.
{
res.push_back(ans);
for (i = ; i < y; i++)//回溯
{
ans.pop_back();
}
return;
}
// if(y+2<=n-1)
getIP(s,x+y , ,res,ans,sum+);
// if(y+3<=n-1)
getIP(s, x+y , ,res,ans,sum+);
// if(y+4<=n-1)
getIP(s, x+y, ,res,ans,sum+);
ans.pop_back();
for (i = ; i < y; i++)
ans.pop_back();
return;
}
public:
vector<string> restoreIpAddresses(string s) {
int n = s.size();
vector<string>res;
string ans;
ans.clear();
getIP(s, , , res, ans, );
ans.clear();
getIP(s, , , res, ans, );
ans.clear();
getIP(s, , , res, ans, );
return res;
}
};

最新文章

  1. taskkill批量删除进程命令
  2. readonly
  3. 转载《遭受arp攻击怎么办》
  4. web.xml中在Servlet中获取context-param和init-param内的参数
  5. Http Header里的Content-Type
  6. mac VPN配置
  7. 学习笔记——Ant
  8. 手动实现 KVO
  9. 【C++深入浅出】设计模式学习之观察者模式
  10. 解决关于IIS10.0下无法安装 URL 重写模块 2的问题
  11. HDU 2152 Fruit
  12. iOS中怎样加入自己定义的字体
  13. Unity3D获取资源的方法整理:
  14. SOA专题---Dropwizard与Spring Boot比较
  15. CentOS 安装 Ansible 以及连接Windows server的办法
  16. 初尝Spring Cloud Config
  17. EOS源码
  18. Java 控制类的引用类型,合理使用内存
  19. C#基础の迭代器详解
  20. Yii2 创建新项目目录

热门文章

  1. C++设计实现一个不能被继承的类
  2. BP
  3. asp.net 访问页面访问统计实现
  4. d9
  5. Codeforces 670F - Restore a Number - [字符串]
  6. 深度学习中将类别标签映射到one_hot向量
  7. 利用Python的collections包下Counter的类统计每个数据出现的个数
  8. Away3D引擎学习入门笔记
  9. hadoop内存配置方案
  10. Java之旅_面向对象_封装