-
复原IP地址
class Solution {
public:
bool isValid(string s, int start, int end)
{
if (start > end) {
return false;
}
if (s[start] == '0' && start != end) { // 0开头的数字不合法
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) { // 如果大于255了不合法
return false;
}
}
return true;
}
void backtracking(string s, int start)
{
if(start == s.size())
{
if(path.size() == 4)
{
string str;
str += path[0];
for(int i = 1; i < 4; ++i)
{
str += "." + path[i];
}
ret.push_back(str);
}
return;
}
for(int i = start; i < s.size(); ++i)
{
if(isValid(s, start, i))
{
path.push_back(s.substr(start, i-start+1));
}
else
{
continue;
}
backtracking(s, i+1);
path.pop_back();
}
}
vectorrestoreIpAddresses(string s) {
backtracking(s, 0);
return ret;
}
private:
vectorpath;
vectorret;
}; -
子集
class Solution {
public:
void backtracking(vector&nums, int start)
{
if(!path.empty())
{
ret.push_back(path);
}
if(start == nums.size())
{
return;
}
for(int i = start; i < nums.size(); ++i)
{
path.push_back(nums[i]);
backtracking(nums, i+1);
path.pop_back();
}
}
vector<vector> subsets(vector & nums) {
ret.push_back(vector{});
backtracking(nums, 0);
return ret;
}
private:
vectorpath;
vector<vector> ret;
}; -
子集II
class Solution {
public:
void backtracking(vector
{
if(!path.empty())
{
ret.push_back(path);
}
if(start == nums.size())
{
return;
}
for(int i = start; i < nums.size(); ++i)
{
if(i > 0 && nums[i] == nums[i-1] && used[i-1] == 0)
{
continue;
}
used[i] = 1;
path.push_back(nums[i]);
backtracking(nums, i+1, used);
path.pop_back();
used[i] = 0;
}
}
vector<vector
sort(nums.begin(), nums.end());
ret.push_back(vector
vector
backtracking(nums, 0, used);
return ret;
}
private:
vector
vector<vector
};