93.复原ip地址
题解
bool isRight(const string& s, int start, int end) {
if (start > end) {
return false;
}
if (s[start] == '0' && start != end) {
return false;
}
int sum = 0;
for (int i = start; i <= end; i++) {
if (s[i] < '0' || s[i] > '9') {
return false;
}
sum = sum * 10 + (s[i] - '0');
if (sum > 255) {
return false;
}
}
return true;
}
vector<string> result;
void back_tracking(string& s, int startIndex, int pointNums) {
if (pointNums == 3) {
if (isRight(s, startIndex, s.size() - 1)) {
result.push_back(s);
}
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (isRight(s, startIndex, i)) {
s.insert(s.begin() + i + 1, '.');
pointNums++;
back_tracking(s, i + 2, pointNums);
s.erase(s.begin() + i + 1);
pointNums--;
} else break;
}
return;
}
vector<string> restoreIpAddresses(string s) {
back_tracking(s, 0, 0);
return result;
}
总结
与字符串切割类似。
78.子集
题解
vector<int> path;
vector<vector<int>> result;
void back_tracking(vector<int>& nums, int startIndex) {
result.push_back(path);
if (startIndex >= nums.size()) {
return;
}
for (int i = startIndex; i < nums.size(); i++) {
path.push_back(nums[i]);
back_tracking(nums, i + 1);
path.pop_back();
}
return;
}
vector<vector<int>> subsets(vector<int>& nums) {
back_tracking(nums, 0);
return result;
}
总结
待更新
90.子集2
待更新