回溯算法part04 93. 复原IP地址 78. 子集 90. 子集 II
93. 复原 IP 地址
class Solution {
private:vector<string> result;bool isValid(string& s,int start,int end){if (start > end) return false;if (s[start] == '0' && start != end) { // 0开头的数字不合法 "0.1.2.201"特殊情况return false;}for (int i = start; i <= end; i++) {if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法return false;}}int num = stoll(s.substr(start,end-start+1)); //stoi会产生报错,out of rangeif(num>255) return false;return true;}
public:void backtracking(string& s,int startIndex,int pointSum){ //startIndex记录向下递归初始层,pointSum递归退出条件if(pointSum==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,'.');pointSum++;backtracking(s,i+2,pointSum);pointSum--;s.erase(s.begin()+i+1);}}}vector<string> restoreIpAddresses(string s) {if(s.size()>12||s.size()<4) return result; //剪枝backtracking(s,0,0);return result;}
};
78. 子集
class Solution {
private:vector<vector<int>> result;vector<int> path;
public:void backTracking(vector<int>& nums,int startIndex){result.push_back(path); // 收集子集,要放在终止添加的上面,否则会漏掉自己if(startIndex>=nums.size()) return; // 终止条件可以不加 forloop已经是退出循环条件了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) {backTracking(nums,0);return result;}
};
90. 子集 II
40.组合总和II+78. 子集,简单题叠加,直接上代码
class Solution {
private:vector<vector<int>> result;vector<int> path;
public:void backTracking(vector<int>& nums,int startIndex){result.push_back(path);for(int i = startIndex;i<nums.size();i++){if(i>startIndex&&nums[i]==nums[i-1]) continue;path.push_back(nums[i]);backTracking(nums,i+1);path.pop_back();}}vector<vector<int>> subsetsWithDup(vector<int>& nums) {sort(nums.begin(),nums.end());backTracking(nums,0);return result;}
};