18. 4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.


使用三重for循环,在最后一层使用哈希表,复杂度为O(n^3),为了避免重复的解,使用set存储得到的vector

class Solution {
public:
    vector > fourSum(vector& nums, int target) {
        int len = nums.size();
        set> data;
        unordered_map data_map;
        sort(nums.begin(), nums.end());
        for(int i=0;i k){
                        vector temp = {nums[i], nums[j], nums[k], findNum};
                        data.insert(temp);
                    }
                }
            }
        }
        return vector>(data.begin(), data.end());
    }
};

你可能感兴趣的:(18. 4Sum)