先写判断字符串是否满足要求
递归需要一个参数来记录已经加入多少个".",当已有3个时,直接判断剩余是否满足,满足则加入答案
class Solution {
public:
vector<string> ans;
string path = "";
bool is_valid(string &s, int start, int end) {
if (start > end) return false;
if (start == end) return true;
if (s[start] == '0' || end - start > 2) return false;
int num = 0;
for (int i = start; i <= end; i++) {
num = num * 10 + s[i] - '0';
}
if (num > 255) return false;
return true;
}
void dfs(string &s, int start_index, int count) {
if (count == 3) {
if (is_valid(s, start_index, s.size() - 1)){
string tmp = path + s.substr(start_index, s.size() - start_index);
ans.emplace_back(tmp);
}
return;
}
for (int i = start_index; i < s.size(); i++) {
if (is_valid(s, start_index, i)) {
path += s.substr(start_index, i - start_index + 1);
path += ".";
dfs(s, i + 1, count + 1);
path.erase(path.end() - (i - start_index + 2), path.end());
} else break;
}
}
vector<string> restoreIpAddresses(string s) {
dfs(s, 0, 0);
return ans;
}
};
普通的回溯
class Solution:
def subsets(self, nums: List[int]):
ans = []
path = []
def dfs(start):
ans.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
dfs(i + 1)
path.pop()
dfs(0)
return ans
添加一个去重逻辑
class Solution:
def subsetsWithDup(self, nums: List[int]):
ans = []
path = []
nums.sort()
def dfs(start):
ans.append(path[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
path.append(nums[i])
dfs(i + 1)
path.pop()
dfs(0)
return ans