If you approach it with BruteForce, u will get time exceeded on the Leetcode, So have to come up with the Hash Data Structure (Since Hash data structure has O(1) Time Complexity to find, it would be effective way to problem solving)
First of all, We can think of the 4 Sum as 2 Sum + 2 Sum. So, if 2 Sum + 2 Sum equals to target, I can take that case into the answer array.
1. Using the Hash table, let the 2 Sum value be the Sum of the pair of the elements in the array.
2. if, once we select the one item of the hash table, nums[i] + nums[j] is a key and the pair (i, j) is the value.
3. Take each item of the hash and let the sum as key be the 'a' while looping and check if the key, (target - a) exists in the hash.
4. if that key exists and doesn't have any duplicated index, put that value set(nums[x],nums[y], nums[z],nums[k]) into the tmp with sorted. Since Using the set Structure, I don't need to consider the duplicated combinations of the value array.
5. with the set, put All the elements of the set into the ans, 2-dim vector of integer.
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ans = {};
if (nums.size()<4){
return {};
}
sort(nums.begin(), nums.end());
unordered_map<int, vector<pair<int,int>>> hash;
set<vector<int>> ans_set;
// Put All the pairs in the nums array into Hash Data Structure
int n = nums.size();
for(int i = 0; i < n-1; i++){
for(int j = i+1; j < n; j++){
int a = nums[i]+nums[j];
hash[nums[i]+nums[j]].push_back(make_pair(i, j));
if(hash.count(target-a)>0){
for(auto &p: hash[target-a]){
if((p.first != i && p.second != j)&&(p.first != j && p.second != i)){
vector<int> order = {i,j,p.first, p.second};
sort(order.begin(),order.end());
vector<int> tmp = {};
for(int k= 0; k < order.size(); k++){
tmp.push_back(nums[order[k]]);
}
ans_set.insert(tmp);
}
}
}
}
}
for(auto it = ans_set.begin(); it != ans_set.end(); ++it){
ans.push_back(*it);
}
return ans;
}
Time Complexity: O(n^2) (only if the size of the input, nums array is 4)
'알고리즘_개념 및 문제풀이 ' 카테고리의 다른 글
리트코드/Leetcode/부분수열의 최댓값 (0) | 2019.10.05 |
---|---|
리트코드/leetcode/배열 중복 제거/remove-duplicates-from-sorted-array (0) | 2019.10.05 |
Leetcode/count_primes/Hash/리트코드 (0) | 2019.09.28 |
Leetcode/jewels and stones/해시/Hash (0) | 2019.09.28 |
백준온라인저지(BOJ)/#9613//GCD(최대공약수)/C++/유클리드 호제법(Euclidean Algorithm) (0) | 2019.08.04 |