Leetcode中有很多“N Sum”问题,这种问题就是给出一个数组A,一个目标数T,然后计算得出在A中有多少数种的组合,使得其和刚好是T.
问题如下:
2 Sum: https://leetcode.com/problems/two-sum/
2 Sum Input array is sorted: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted
3 Sum: https://leetcode.com/problems/3sum
3 sum-closest: https://leetcode.com/problems/3sum-closest/
4 Sum: https://leetcode.com/problems/4sum/
4 SumII: https://leetcode.com/problems/4sum-ii/
首先从最简单的2 Sum Input array is sorted: 问题来看
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
由于数组是已经排序的,那么我们可以知道数组中最小的数是nums[0]
,最大的是nums[nums.size() - 1]
。设置两个index,一个叫front,初始值为0,另外一个叫back,初始值为nums.size() - 1。求nums[front] + nums[back],如果和大于target,那么就将back减一,如果小于,就将front 加1。
将上述思路整理成代码。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
int front = 0;
int back = nums.size() - 1;
while(front < back) {
int t = nums[front] + nums[back] ;
if(t == target) {
res.push_back(front + 1);
res.push_back(back + 1);
return res;
}
else if(t > target)
back --;
else
front ++;
}
return res;
}
};
上述解法复杂度为O(N),算是比较理想的解法了。有了这个基础,我们看下面的题。
3 Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:[ [-1, 0, 1], [-1, -1, 2] ]
由于我们已经做了 2 Sum问题,那么这个题可以转化(下降)为2 Sum问题。然后采用上面的算法来做。代码如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());//排序
unsigned int i;
for (i = 0; i < nums.size(); ++i) {
int target = -nums[i];//这里转化为了2 Sum问题
int front = i + 1;
int back = nums.size() - 1;
while(front < back) {
int sum = nums[front] + nums[back];
if(sum < target)
front++;
else if(sum > target)
back--;
else {
vector<int> triple(3,0);
triple[0] = nums[i];
triple[1] = nums[front];
triple[2] = nums[back];
res.push_back(triple);
//跳过相同的数字
while(front < back && nums[front]== triple[1])
front ++;
while(front < back && nums[back] == triple[2])
back--;
}
}
while(i + 1 < nums.size() && nums[i] == nums[i + 1])
i++;
}
return res;
}
};
下面的4 Sum问题也可以变为3 Sum然后变为2 Sum来解决。
https://leetcode.com/problems/4sum/#/description
剩下的几个题比较特殊,因为不能用排序打乱顺序,这就需要用到hash表来存储。我留到下次再总结吧。