leetcode: 4Sum

http://oj.leetcode.com/problems/4sum/

Given an array S of n integers, are there elements a, b, c, 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:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
    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)
 

思路

3Sum的代码扩展一下搞定。

 1 class Solution {
 2 public:
 3     void threeSum(vector<int> &num, int start_index, int target, int v1, vector<vector<int> > &result) {
 4         int size = num.size();
 5         
 6         for (int i = start_index; i < size - 2; ) {
 7             int j = i + 1, k = size - 1, tmp;
 8             
 9             while (j < k) {
10                 int sum = v1 + num[i] + num[j] + num[k];
11                 
12                 if (target == sum) {
13                     vector<int> r;
14                     
15                     r.push_back(v1);
16                     r.push_back(num[i]);
17                     r.push_back(num[j]);
18                     r.push_back(num[k]);
19                     result.push_back(r);
20                 }
21                 
22                 if (sum < target) {
23                     tmp = j + 1;
24                     
25                     while ((tmp < k) && (num[j] == num[tmp])) {
26                         ++tmp;
27                     }
28                     
29                     j = tmp;
30                 }
31                 else {
32                     tmp = k - 1;
33                     
34                     while ((tmp > j) && (num[tmp] == num[k])) {
35                         --tmp;
36                     }
37                     
38                     k = tmp;
39                 }
40             }
41             
42             tmp = i + 1;
43             
44             while ((tmp < (size - 2)) && (num[i] == num[tmp])) {
45                 ++tmp;
46             }
47             
48             i = tmp;
49         }
50     }
51     
52     vector<vector<int> > fourSum(vector<int> &num, int target) {
53         vector<vector<int> > result;
54         int size = num.size(), tmp;
55         
56         sort(num.begin(), num.end());
57         
58         for (int i = 0; i < (size - 3); ) {
59             threeSum(num, i + 1, target, num[i], result);
60             
61             tmp = i + 1;
62             
63             while ((tmp < (size - 3)) && (num[i] == num[tmp])) {
64                 ++tmp;
65             }
66             
67             i = tmp;
68         }
69         
70         return result;
71     }
72 };

 

posted @ 2013-10-28 16:23  移山测试工作室黑灯老师  阅读(454)  评论(0编辑  收藏  举报
count website visits
Buy Computers