third height depth-first search and arrangement to remove duplicate result(c++)


  • 0
    L

    #include <vector>
    #include <algorithm>

    class Solution {
    public:

    void searchThreeSum(vector<int>& nums, int from, vector<int> subRst, vector<vector<int>>& rst) {
        if (subRst.size() >= 3) {
            if (subRst[0] + subRst[1] + subRst[2] == 0)   rst.push_back(subRst);
            return;
        }
        for (int i = from; i < nums.size(); i++) {
            if (i == from || nums[i] != nums[i - 1]) {
                subRst.push_back(nums[i]);
                searchThreeSum(nums, i + 1, subRst, rst);
                subRst.pop_back();
            }
        }
    }
    
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> rst;
    
        if (nums.size() < 3)    return rst;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 2; i++) {
            vector<int> subRst;
            subRst.push_back(nums[i]);
            if (i == 0 || nums[i] != nums[i - 1]) {
                searchThreeSum(nums, i + 1, subRst, rst);
            }
        }
    
        return rst;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.