1、复原IP地址
复原IP地址
class Solution {
public:
bool isValid(string s, int start, int end) {
if (start > end) return false;
if (s[start] == '0' && start != end) return false;
int num = 0;
for (int i = start; i <= end; i++) {
if (s[i] > '9' || s[i] < '0') return false;
num = num * 10 + (s[i] - '0');
if (num > 255) return false;
}
return true;
}
void backtracking(string &s, int startIndex, int getNode, vector<string>& result) {
if (getNode == 3) {
if (isValid(s, startIndex, s.size() - 1)) {
result.push_back(s);
}
return ;
}
for (int i = startIndex; i < s.size(); i++) {
if (isValid(s, startIndex, i)) {
s.insert(s.begin() + i + 1, '.');
backtracking(s, i + 2, getNode + 1, result);
s.erase(s.begin() + i + 1);
} else break;
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> result;
if (s.size() < 4 || s.size() > 12) return result;
backtracking(s, 0, 0, result);
return result;
}
};
2、子集
子集
class Solution {
public:
void backtracking(vector<int>& nums, int startIndex, vector<vector<int>>& result, vector<int>& path) {
result.push_back(path);
if (startIndex >= nums.size()) return ;
for (int i = startIndex; i < nums.size(); i++) {
path.push_back(nums[i]);
backtracking(nums, i + 1, result, path);
path.pop_back();
}
return ;
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result;
vector<int> path;
backtracking(nums, 0, result, path);
return result;
}
};
3、子集Ⅱ
子集Ⅱ
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIndex, vector<bool>& used) {
result.push_back(path);
if (startIndex >= nums.size()) return ;
for (int i = startIndex; i < nums.size(); i++) {
if (i > 0 && nums[i - 1] == nums[i] && used[i - 1] == false) continue;
path.push_back(nums[i]);
used[i] = true;
backtracking(nums, i + 1, used);
path.pop_back();
used[i] = false;
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
backtracking(nums, 0, used);
return result;
}
};