本文主要是介绍【代码随想录算法训练营第37期 第二十八天 | LeetCode93.复原IP地址、78.子集、90.子集II】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码随想录算法训练营第37期 第二十八天 | LeetCode93.复原IP地址、78.子集、90.子集II
一、93.复原IP地址
解题代码C++:
class Solution {
private: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;}for(int i = startIndex; i < s.size(); i ++){if(isValid(s, startIndex, i)){s.insert(s.begin() + i + 1, '.');pointNum ++;backtracking(s, i + 2, pointNum);pointNum --;s.erase(s.begin() + i + 1);}else break;}}bool isValid(const 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;}public:vector<string> restoreIpAddresses(string s) {result.clear();if(s.size() < 4 || s.size() > 12) return result;backtracking(s, 0, 0);return result;}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0093.%E5%A4%8D%E5%8E%9FIP%E5%9C%B0%E5%9D%80.html
二、78.子集
解题代码C++:
class Solution {
private: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();}}public:vector<vector<int>> subsets(vector<int>& nums) {result.clear();path.clear();backtracking(nums, 0);return result;}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0078.%E5%AD%90%E9%9B%86.html
三、90.子集II
解题代码C++:
class Solution {
private:vector<vector<int>> result;vector<int> path;void backtracking(vector<int>& nums, int startIndex, vector<bool>& used){result.push_back(path);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;backtracking(nums, i + 1, used);used[i] = false;path.pop_back();}}public:vector<vector<int>> subsetsWithDup(vector<int>& nums) {result.clear();path.clear();vector<bool> used(nums.size(), false);sort(nums.begin(), nums.end());backtracking(nums, 0, used);return result;}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0090.%E5%AD%90%E9%9B%86II.html
这篇关于【代码随想录算法训练营第37期 第二十八天 | LeetCode93.复原IP地址、78.子集、90.子集II】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!