LeetCode18 4Sum

题意:

Given an array S of n integers, are there elements abc, and d in S 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.(Medium)

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

 分析:

还是采取跟2sum,3sum一样的思路,先排序,再two pointers.

实现的时候利用3sum,然后加一层循环,复杂度O(n^3).

代码:

 1 class Solution {
 2 private:
 3     vector<vector<int>> threeSum(vector<int>& nums, int target) {
 4         vector<vector<int>> v;
 5         if (nums.size() < 3) {  //数组元素个数过少,直接返回
 6             return v;
 7         }
 8         for (int i = 0; i < nums.size() - 2; ++i) {
 9             if (i >= 1 && nums[i] == nums[i - 1]) {
10                 continue;
11             } 
12             int start = i + 1, end = nums.size() - 1;
13             while (start < end) {
14                 if ( nums[i] + nums[start] + nums[end] == target ) {
15                     vector<int> temp{nums[i], nums[start], nums[end]};
16                     v.push_back(temp);
17                     start++;
18                     end--;
19                     while ( (start < end) && nums[start] == nums[start - 1]) { //没加start < end虽然过了,估计是样例不够完善
20                         start++;
21                     }
22                     while ( (start < end) && nums[end] == nums[end + 1]) {
23                         end--;
24                     }
25                 }
26                 else if (nums[i] +  nums[start] + nums[end] > target ) {
27                     end--;
28                 }
29                 else {
30                     start++;
31                 }
32             }
33         }
34         return v;
35     }
36 public:
37     vector<vector<int>> fourSum(vector<int>& nums, int target) {
38         sort(nums.begin(), nums.end());
39         vector<vector<int>> v;
40         for (int i = 0; i < nums.size(); ++i) {
41             if (i > 0 && nums[i] == nums[i - 1]) {
42                 continue;
43             }
44             vector<int> temp(nums.begin() + i + 1, nums.end());
45             vector<vector<int>> result = threeSum(temp, target - nums[i]);
46             for (int j = 0; j < result.size(); ++j) {
47                 result[j].push_back(nums[i]);
48                 v.push_back(result[j]);
49             }
50         }
51         return v;
52     }
53 };

 

posted @ 2016-08-12 22:12  wangxiaobao1114  阅读(215)  评论(0编辑  收藏  举报