1、LeetCode93 复原IP地址
题目链接:93、复原IP地址
首先判断终止条件,一共有3个“.”,当PointNum == 3时,判断剩余数字是否合法,如果合法,将分割好的s加入数组result。
如何判断是否合法? isValid(string& s, int start, int end);
1、start > end return false 因为在递归时,会backtracking(s, i + 2, PointNum),i + 2可能会超过最后一个元素,因此需要判断是否start > end。
2、s[i] < '0' || s[i] > '9' return false;
3、将字符串转换为数字,判断是否大于255,如何将字符串转换为数字,num=num*10 + s[i] - '0';
如果合法, s.insert(s.begin() + i + 1, '0'); PointNum ++;
class Solution {
public:
vector<string> result;
void backtracking(string& s, int startIndex, int PointNum)
{
if (PointNum == 3)
{
if (isValid(s, startIndex, s.size() - 1))
{
result.push_back(s);
return;
}
//return;
}
for (int i = startIndex; i < s.size(); i++)
{
if (isValid(s, startIndex, i))
{
s.insert(s.begin() + i + 1, '.');
PointNum += 1;
backtracking(s, i + 2, PointNum);
PointNum -= 1;
s.erase(s.begin() + i + 1);
}
else
{
break;
}
}
}
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] < '0' || s[i] > '9')
{
return false;
}
num = num * 10 + s[i] - '0';
if (num > 255)
{
return false;
}
}
return true;
}
vector<string> restoreIpAddresses(string s) {
result.clear();
if (s.size() < 4 || s.size() > 12) return result;
backtracking(s, 0, 0);
return result;
}
};
2、LeetCode78子集
题目链接:78、子集
之前的题都是在终止条件时收集结果,比如if (path.size()==k) result.push_back(path);
本题求子集,每一次递归都要收集一次结果。
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(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]);
backtracking(nums, i + 1);
path.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};
3、LeetCode90子集II
题目链接:90、子集II
与LeetCode40组合总和II类似,40、组合总和II
vector<bool> used(nums.size(), false);
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtraking(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] == nums[i - 1] && used[i - 1] == false)
{
continue;
}
path.push_back(nums[i]);
used[i] = true;
backtraking(nums, i + 1, used);
used[i] = false;
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<bool> used(nums.size(), false);
result.clear();
path.clear();
sort(nums.begin(), nums.end());
backtraking(nums, 0, used);
return result;
}
};