代码随想录算法训练营 | 回溯算法part03

93.复原IP地址

93.复原IP地址

cpp 复制代码
class Solution {
private:
    vector<string> res;
    string temp;
    void backtracing(string& s, int startIndex, int cnt) {
        if (cnt > 4) {  // 是否是四位整数
            return;
        }
        if (cnt == 4 && startIndex >= s.size()) {
            res.push_back(temp.substr(0, temp.size() - 1)); // 去掉最后一个'.'
            return;
        }
        for (int i = startIndex; i < s.size(); ++i) {
            string str = s.substr(startIndex, i - startIndex + 1); // 切割子串
            if (str.size() >= 4) { // 防止转换为数字的时候溢出
                continue;
            }
            int num = stoi(str);
            if ((str.size() == 1 || (str.size() > 1 && str[0] != '0')) && (num >= 0 && num <= 255)) { // 不含前导零,且范围在[0,255]之间
                temp += str;
                temp.push_back('.');
            } else {
                continue;
            }
            backtracing(s, i + 1, cnt + 1);
            temp.pop_back(); // 回溯 去'.'
            temp = temp.substr(0, temp.size() - str.size()); // 去str
        }
    }
public:
    vector<string> restoreIpAddresses(string s) {
        res.clear();
        temp.clear();
        backtracing(s, 0, 0);
        return res;
    }
};

78.子集

78.子集

收集树中的所有节点

cpp 复制代码
class Solution {
private:
    vector<vector<int>> res;
    vector<int> temp;
    void backtracing(vector<int>& nums, int startIndex) {
        res.push_back(temp);
        for (int i = startIndex; i < nums.size(); ++i) {
            temp.push_back(nums[i]);
            backtracing(nums, i + 1);
            temp.pop_back();
        }
    }
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        backtracing(nums, 0);
        return res;
    }
};

90.子集II

90.子集II

cpp 复制代码
class Solution {
private:
    vector<vector<int>> res;
    vector<int> temp;
    void backtracing(vector<int>& nums, vector<bool>& used, int startIndex) {
        res.push_back(temp);
        for (int i = startIndex; i < nums.size(); ++i) {
            if (i > 0 && used[i - 1] == false && nums[i] == nums[i - 1]) {
                continue;
            }
            used[i] = true;
            temp.push_back(nums[i]);
            backtracing(nums, used, i + 1);
            used[i] = false;
            temp.pop_back();
        }
    }

public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<bool> used(nums.size(), false);
        backtracing(nums, used, 0);
        return res;
    }
};
相关推荐
Gyoku Mint33 分钟前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
纪元A梦35 分钟前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法
fpcc43 分钟前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
px不是xp1 小时前
山东大学算法设计与分析复习笔记
笔记·算法·贪心算法·动态规划·图搜索算法
终焉代码1 小时前
STL解析——list的使用
开发语言·c++
DevangLic2 小时前
【 *p取出内容 &a得到地址】
c++
枫景Maple2 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
鑫鑫向栄2 小时前
[蓝桥杯]修改数组
数据结构·c++·算法·蓝桥杯·动态规划
鑫鑫向栄2 小时前
[蓝桥杯]带分数
数据结构·c++·算法·职场和发展·蓝桥杯