跟3sum和3sum closest差不多
C++:
1 class Solution { 2 public: 3 vector<vector<int> > fourSum(vector<int> &num, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<vector<int>> ret; 7 if (num.size() < 4) return ret; 8 sort(num.begin(), num.end()); 9 for (int i = 0; i < num.size()-3; i++) { 10 if (i > 0 && num[i] == num[i-1]) continue; 11 for (int j = i+1; j < num.size()-2; j++) { 12 if (j > i+1 && num[j] == num[j-1]) continue; 13 int end = num.size()-1; 14 for (int beg = j+1; beg < end; beg++) { 15 if (beg > j+1 && num[beg] == num[beg-1]) continue; 16 int sum = num[i] + num[j] + num[beg] + num[end]; 17 if (sum == target) { 18 vector<int> tmp; 19 tmp.push_back(num[i]); 20 tmp.push_back(num[j]); 21 tmp.push_back(num[beg]); 22 tmp.push_back(num[end]); 23 ret.push_back(tmp); 24 } 25 else if (sum > target) end--, beg--; 26 } 27 } 28 } 29 return ret; 30 } 31 };
java:
1 public class Solution { 2 public List<List<Integer>> fourSum(int[] nums, int target) { 3 List<List<Integer>> ans = new ArrayList<List<Integer>>(); 4 Arrays.sort(nums); 5 for (int i = 0; i < nums.length; i++) 6 { 7 if (i > 0 && nums[i] == nums[i-1]) continue; 8 for (int j = i+1; j < nums.length; j++) 9 { 10 if (j > i+1 && nums[j] == nums[j-1]) continue; 11 int left = j+1; 12 int right = nums.length-1; 13 while (left < right) 14 { 15 if (left > j+1 && nums[left] == nums[left-1]) { 16 left++; 17 continue; 18 } 19 int sum = nums[i] + nums[j] + nums[left] + nums[right]; 20 if (sum == target) { 21 List<Integer> tmp = new ArrayList<Integer>(); 22 tmp.add(nums[i]); 23 tmp.add(nums[j]); 24 tmp.add(nums[left]); 25 tmp.add(nums[right]); 26 ans.add(tmp); 27 left++; 28 } 29 else if (sum < target) left++; 30 else right--; 31 } 32 } 33 } 34 return ans; 35 } 36 }