题意
给定一个字符串划分成4个子串,每个子串我都要满足0<= x <= 255,并且不能出现 x = “01”(不能以0开头的串)返回所有满足条件的组合
e.g. s = "25525511135"
out = ["255.255.11.135","255.255.111.35"]
题目链接
https://leetcode.com/problems/restore-ip-addresses/description/
思路
dfs遍历整个字符串。
退出条件如果切分的数量 >4退出dfs。如果切分数量为4并且所有所有的4个子串都满足0 <= x <= 255,加入答案,也要退出dfs。
dfs中还要保存当前遍历的起始位置,每一层dfs需要截取起始位置1位,2位,3位,判断截取的字符串,0 <= x <=255并且不能存在0开头的情况(除了0),如果截取的字符串满足条件,进入下一层dfs。
注意
由于我判断结束的条件是字符串的最后一位的下一位,index + i <= s.size()
所以我需要for循环的遍历中小于等于字符串的长度,不然会导致问题。
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
string temp;
dfs(0, 0, s, temp, ret);
return ret;
}
void dfs(int index, int cnt, string& s, string& temp, vector<string>& ret) {
if (cnt > 4) {
return;
}
if(index == s.size()) {
if (cnt == 4) {
//delete the dot
temp = temp.substr(0, temp.size()-1);
ret.push_back(temp);
}
return;
}
for(int i = 1; i <= 3 && index + i <= s.size(); i++) {
string newStr = s.substr(index,i);
if (newStr[0] == '0' && newStr.size() > 1) {
break;
}
if (stoi(newStr) <= 255) {
string cur = temp;
temp += newStr;
temp += ".";
dfs(index + i, cnt + 1, s, temp, ret);
temp = cur;
}
}
}
};
时间复杂度:
O
(
3
4
)
O(3^4)
O(34) 最多有4层,每一层最多有3个分叉。常数时间
空间复杂度:
O
(
16
)
O(16)
O(16) 常数空间