今日记录


93.复原IP地址

Leetcode链接

class Solution {
private:
    vector<string> result;
    void backtracking(string s, int index, int pointNum) {
        if (pointNum == 3) {
            if (isValid(s, index, s.size() - 1)) {
                result.push_back(s);
            }
            return;
        }
        for (int i = index; i < s.size(); i++) {
            if (isValid(s, index, i)) {
                s.insert(s.begin() + i + 1, '.');
                pointNum++;
                backtracking(s, i + 2, pointNum);
                pointNum--;
                s.erase(s.begin() + i + 1);
            } else
                break;
        }
    }

    bool isValid(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;
    }
};

78.子集

Leetcode链接

class Solution {
private:
    vector<vector<int>> result;
    vector<int> path;
    void backtracking(vector<int>& nums, int index) {
        result.push_back(path);
        if (index >= nums.size()) {
            return;
        }
        for (int i = index; 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;
    }
};

90.子集Ⅱ

Leetcode链接

重点在于去重的思路:
同一树层不能重复读取,同一树枝可以重复选取

判断方法:

if (i > index && nums[i] == nums[i - 1]) {
    continue;
}
class Solution {
private:
    vector<vector<int>> result;
    vector<int> path;
    void backtracking(vector<int>& nums, int index) {
        result.push_back(path);
        for (int i = index; i < nums.size(); i++) {
            if (i > index && nums[i] == nums[i - 1]) {
                continue;
            }
            path.push_back(nums[i]);
            backtracking(nums, i + 1);
            path.pop_back();
        }
    }

public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        result.clear();
        path.clear();
        sort(nums.begin(), nums.end());
        backtracking(nums, 0);
        return result;
    }
};

总结

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部