Day24 回溯法4 | LeetCode 93. 复原 IP 地址, 78. 子集, 90. 子集 II

LeetCode 93. 复原 IP 地址

class Solution {
public:
    vector result;
    void backTracking(string& s, int startIndex, int poingNum){
        if (poingNum == 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)){
                continue;
            }
            s.insert(s.begin() + i + 1, '.');
            backTracking(s, i + 2, poingNum + 1);
            s.erase(s.begin() + i + 1);
        }
    }


    vector restoreIpAddresses(string s) {
        backTracking(s, 0, 0);
        return result;
    }
    bool isValid(string& s, int start, int end){
        if(start > end){
            return false;
        }
        if (s[start] == '0' && start != end){
            return false;
        }
        int sum = 0;
        for (int i = start; i <= end; i++){
            if (s[i] > '9' || s[i] < '0'){
                return false;
            }
            sum = sum * 10 + s[i] - '0';
            if (sum > 255){
                return false;
            }
        }
        return true;
    }
};

LeetCode 78. 子集

class Solution {
public:
    vector path;
    vector> result;

    void backTracking(vector& nums, int startIndex){
        
        result.push_back(path);

        for (int i = startIndex; i < nums.size(); i++){
            path.push_back(nums[i]);
            backTracking(nums, i + 1);
            path.pop_back();   
        }
    }
    vector> subsets(vector& nums) {
        backTracking(nums, 0);
        return result;
    }

};

LeetCode 90. 子集 II

class Solution {
public:
    vector path;
    vector> result;

    void backTracking(vector& 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> subsetsWithDup(vector& nums) {
        sort(nums.begin(), nums.end());
        backTracking(nums, 0);
        return result;
    }
};

你可能感兴趣的:(算法学习,leetcode,算法,职场和发展)