K-Sum

很经典的题目,以LeetCode上的4-Sum为例说明。

题目

https://leetcode.com/problems/4sum/description/

-w949

想法

递归的进行,把 k Sum 分解成 K-1 Sum,直到 2 Sum!!!

可能效率不是最高的,但代码应该是最清楚的

复杂度还是很高的,O( N^k-1 )

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
private:
vector<vector<int>> kSum(vector<int>& nums, int target, int k, int start) {
vector<vector<int>> res;
if (nums.size() - start < k)
return res;
if (k == 2) {
int l = start, r = nums.size() - 1;
while (l < r) {
if (nums[l] + nums[r] == target) {
res.push_back({nums[l], nums[r]});
l++;
while (l < r && nums[l] == nums[l - 1])
l++;
r--;
while (l < r && nums[r] == nums[r + 1])
r--;
} else if (nums[l] + nums[r] < target) {
l++;
} else {
r--;
}
}
} else {
int i = start;
while (i < nums.size() - k + 1) {
vector<vector<int>> subRes = kSum(nums, target - nums[i], k - 1, i + 1);
if (!subRes.empty()) {
for (auto r : subRes) {
r.insert(r.begin(), nums[i]);
res.push_back(r);
}
}
i++;
while (i < nums.size() && nums[i] == nums[i - 1])
i++;
}
}
return res;
}
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
return kSum(nums, target, 4, 0);
}
};