问题描述:
给定一个整形数组 nums[], 一个整形目标值target。从数组nums[]中找到k个数,满足这k个数之和为target,找到所有这样的组合,相同的组合只能出现一次。
本文致力于寻找一个通用的方法来解决KSUM问题。参考文章http://www.sigmainfy.com/blog/4sum-problem-analysis-different-time-complexity.html,在此对作者表示感谢
以下为代码用C++是实现,本代码在leetcode 18: 4sum上为Accepted,但运行时间较长,望大家见谅。
class Solution {
public:
vector<vector<int>> findZeroSumInSortedArr(vector<int>& nums, vector<int>::size_type begin, int count, int target) {
vector<vector<int>> ret;
if (count == 2) {
vector<int>::size_type left = begin;
vector<int>::size_type right = nums.size() - 1;
vector<int> tuple(2, 0);
while (left < right) {
if (nums[left] + nums[right] < target) {
left++;
}
else if (nums[left] + nums[right] > target) {
right--;
}
else {
tuple[0] = nums[left];
tuple[1] = nums[right];
//去除完全相同的二元组
if (ret.empty() || tuple != *(ret.end() - 1)) {
ret.push_back(tuple);
}
left++;
right--;
}
}
return ret;
}
else {
int curValue = nums[begin]; //去除第一个整数相同的组合
for (vector<int>::size_type ix = begin; ix < nums.size() - count + 1; ix++) {
if (ix > begin && curValue == nums[ix]) {
continue;
}
int newTarget = target - nums[ix];
vector<vector<int>> subRet = findZeroSumInSortedArr(nums, ix + 1, count - 1, newTarget);
vector<int> tuple;
for (vector<vector<int>>::iterator iter = subRet.begin(); iter != subRet.end(); iter++) {
tuple.clear();
tuple.push_back(nums[ix]);
for (vector<int>::iterator subIter = (*iter).begin(); subIter != (*iter).end(); subIter++) {
tuple.push_back(*subIter);
}
ret.push_back(tuple);
}
curValue = nums[ix];
}
return ret;
}
}
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end(), less<int>());
vector<vector<int>> ret;
if (nums.size() < 4) return ret;
return findZeroSumInSortedArr(nums, 0, 4, target);
}
};