93.复原IP地址
题目链接:https://leetcode.cn/problems/restore-ip-addresses/
代码:
class Solution {
public:
vector<string> result;
vector<string> restoreIpAddresses(string s) {
if(s.size() < 4 || s.size() > 12)
return result;
IpAdd(s,0,0);
return result;
}
void IpAdd(string &s, int index, int pointNum)
{
if(pointNum == 3)
{
if (ifValid(s, index, s.size() - 1))
result.push_back(s);
return;
}
for(int i = index; i < s.size(); i++)
{
if(ifValid(s,index,i))
{
s.insert(s.begin() + i + 1,'.');
pointNum++;
IpAdd(s,i+2,pointNum);
pointNum--;
s.erase(s.begin() + i + 1);
}else break;
}
}
bool ifValid(string s, int start, int end)
{
if(start > end)
return false;
if(s[start] == '0' && start != end)
return false;
int sum = 0;
while(start <= end)
{
int cur = s[start] - '0';
if(cur > 9 || cur < 0)
return false;
sum = sum * 10 +cur;
if(sum > 255)
return false;
start++;
}
return true;
}
};
和那个回文串很像,不要怕麻烦,多写几个函数来验证
78.子集
题目链接:https://leetcode.cn/problems/subsets/submissions/
代码:
public:
vector<vector<int>> result;
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> tmp;
group(nums,0,tmp);
return result;
}
void group(vector<int> nums, int startIndex, vector<int> tmp)
{
result.push_back(tmp);
if(startIndex >= nums.size())
return;
for(int i = startIndex; i < nums.size(); i++)
{
tmp.push_back(nums[i]);
group(nums,i+1,tmp);
tmp.pop_back();
}
}
};
result加入的位置注意一下 其实是简单的
90.子集II
题目链接:https://leetcode.cn/problems/subsets-ii/submissions/
class Solution {
public:
vector<vector<int>> result;
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<int> tmp;
back(nums,0,tmp);
return result;
}
void back(vector<int> nums,int startIndex,vector<int> tmp)
{
result.push_back(tmp);
if(startIndex >= nums.size())
return;
for(int i = startIndex; i < nums.size(); i++)
{
if(i > startIndex && nums[i] == nums[i-1])
continue;
tmp.push_back(nums[i]);
back(nums,i+1,tmp);
tmp.pop_back();
}
}
};
40.组合总和II 和 78.子集的集合 不难