一句话经验
There is no coming to consciousness without pain.
没有任何一种觉醒是不带着痛苦的
放轻松,虽然是c++实现,拒绝奇技淫巧,通俗易懂。
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;//输出结果
vector<string> path;//栈保持路径
//从位置0 遍历每个字符串
dfs(s,0,0,path,res);
return res;
}
void dfs(string s,int start,int depth ,vector<string> &path, vector<string> & res)
{
if (start >s.size())
{
return ;//字符串遍历完毕
}
//递归结束条件01
//选取4组后,还有剩余元素 肯定无法组成ip。剪枝
if ( 4 ==depth && start <s.size() )
{
return ;
}
////递归结束条件02 寻找叶子节点。
if ( 4 ==depth && start == s.size() )
{
//拼成ip
string str=path[0];
for (int i = 1;i<4;++i) {
str = str + '.' + path[i];
}
res.push_back(str);//ans中保存一种可行方案
return;
}
//
// 递归变化条件 {2 5 5}
//每一个string只能存长度1~3的字符串
for(int i=1;i<4;i++)
{
//获取当前组 元素
string str = s.substr(start,i);//切割字符串
//约束条件:
if (i == 3 && atoi(str.c_str()) > 255) //不能大于255
return;
if (i != 1 && s[start] == '0') //01,001非法
return;
path.push_back(str);
//下一组元素
dfs(s,start+i,depth+1,path,res);
//pop当前组 元素
path.pop_back();
}
}
};
func restoreIpAddresses(s string) []string {
res:=make([]string,0) //符合高度为4的 3叉树的路径
if len(s) > 12 {
return res //过 12 位的肯定不能是 ip 地址,最大就是 255.255.255.255
}
path :=make([]string,0) //用栈进行回溯
dfs(s,0,0,&path,&res) //空指针修改
return res
}
func dfs(s string, start int,depth int,path* []string, res *[]string){
//01 越界
if start >len(s) {
return
}
if 4 == depth {
//02 剪枝 [2.5.5.2.551113]
if start <len(s) {
return
}
//03 符合条件的路径 "255.255.111.35"
if start ==len(s){
tmp := strings.Join(*path, ".")
*res = append(*res, tmp)
return
}
}
//循环处理
for i:=1;i<4;i++{
if start+i >len(s) {
return
}
temp :=s[start:start+i] //左闭右开
//01 001
if i!=1 && s[start] =='0' {
return
}
if i==3 {
ip, _ := strconv.Atoi(temp);
if ip >255{
continue;
}
}
//////////////////////////////////////////////////
*path = append(*path, temp) //插入最后一个元素
dfs(s, start+i, depth+1,path,res)
//删除最后一个记录,回溯使用
*path = (*path)[:len((*path))-1]
}
}
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.' 分隔。
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
思考 60秒 。。。
思考 60秒 。。
来源:https://leetcode-cn.com/problems/restore-ip-addresses/solution/shou-hua-tu-jie-huan-yuan-dfs-hui-su-de-xi-jie-by-/
来源:https://leetcode-cn.com/problems/restore-ip-addresses/solution/shou-hua-tu-jie-huan-yuan-dfs-hui-su-de-xi-jie-by-/
Permutations II
分享最实用的经验 , 希望每一位来访的朋友都能有所收获! 如果有疑问请联系我,一起探讨,进步。