博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Restore IP Addresses
阅读量:4531 次
发布时间:2019-06-08

本文共 1230 字,大约阅读时间需要 4 分钟。

题目:

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)

思路:递归,回溯

c++代码:

#include 
#include
#include
#include
using namespace std;class Solution {public: vector
restoreIpAddresses(string s) { vector
v; string t = ""; dfs(s, t, v, 1); return v; } void dfs(string s, string t, vector
&v, int count){ if(count == 4){ if(isValid(s)){ v.push_back(t+s); } return; } int i; for(i = 1; i < 4; i++){ if(i < s.size()){ string g = s.substr(0, i); if(isValid(g)){ string m = s.substr(i); dfs(m, t + g + ".", v, count + 1); } } } } bool isValid(string g){ int l = g.size(); if(l > 3)return false; if( l >=2 && g[0] == '0')return false; int vv = atoi(g.c_str()); return vv <= 255 && vv >= 0; }};int main(){ Solution *s = new Solution(); vector
r = s->restoreIpAddresses("1111"); vector
::iterator iter; for(iter = r.begin(); iter != r.end(); iter++){ cout << *iter << endl; } delete s; return 1;}

  

  

转载于:https://www.cnblogs.com/zhutianpeng/p/4272491.html

你可能感兴趣的文章
我的轮播练习
查看>>
js中index()的四种经典用法111
查看>>
vb Array.ConvertAll 泛型方法
查看>>
flask 基本配置和参数解释
查看>>
HDMI转EDP芯片NCS8803简介
查看>>
Git查看、删除、重命名远程分支和tag
查看>>
nexus4/5/6/7/9/10设备谷歌安卓5.1.1系统底包下载
查看>>
子界类型的应用
查看>>
ubuntu系统中查看本机cpu和内存信息的命令和用法
查看>>
PHP的学习--cookie和session
查看>>
es6 箭头函数
查看>>
python装饰器的作用
查看>>
[bzoj2510]弱题 (循环矩阵优化dp)
查看>>
Django Form 的主要内置字段介绍
查看>>
如何写好一个UITableView
查看>>
XML文件生成C++代码(基于rapidxml)
查看>>
写代码,更需要设计代码
查看>>
iOS:修改项目名
查看>>
SpringCloud-Eureka
查看>>
double在输出为字符串的几种方法效率测试
查看>>