数据N个元素的和的组合
目录
/*
写一个函数 void foo(arr, m, n),arr是整数数组,m是个数,n是和,打印所有和为n的
二维数组,注意兼顾性能。 例子: arr 为[-1,1,2,3,4,5,6] m=2, n=5时,打印 [
[1,4],[2,3],[-1,6] ] m=3, n=6时,打印[ [-1,1,6], [-1,2,5], [-1,3,4],
[1,2,3] ]
*/
#include <iostream>
#include <vector>
using namespace std;
void print(vector<vector<int>> group) {
cout << "[";
for (auto &pair : group) {
cout << "[";
for (auto &item : pair) {
cout << item << " ";
}
cout << "\b], ";
}
cout << "\b\b]" << endl;
}
vector<vector<int>> TwoNumSum(int arr[], size_t len, int argSum) {
int i = 0, j = int(len) - 1;
int sum = 0;
vector<vector<int>> ret;
while (i < j) {
sum = arr[i] + arr[j];
if (sum == argSum) {
vector<int> group;
group.push_back(arr[i]);
group.push_back(arr[j]);
ret.push_back(group);
i++;
} else if (sum < argSum) {
i++;
} else {
j--;
}
}
return ret;
}
int TwoNumSum(int arr[], size_t len, int argSum, vector<vector<int>> &ret) {
int add = ret.size();
int i = 0, j = int(len) - 1;
int sum = 0;
while (i < j) {
sum = arr[i] + arr[j];
if (sum == argSum) {
vector<int> group;
group.push_back(arr[i]);
group.push_back(arr[j]);
ret.push_back(group);
i++;
} else if (sum < argSum) {
i++;
} else {
j--;
}
}
return ret.size() - add;
}
int NNumSum(int arr[], int arrLen, int num, int argSum,
vector<vector<int>> &result) {
int add = result.size();
if (num == 2) {
return TwoNumSum(arr, arrLen, argSum, result);
} else {
for (int i = 0; i < arrLen - num; i++) {
int addNum = NNumSum(&arr[i + 1], arrLen - i - 1, num - 1,
argSum - arr[i], result);
if (addNum) {
vector<vector<int>>::iterator iter = result.end() - addNum;
for (; iter != result.end(); iter++) {
iter->push_back(arr[i]);
}
}
}
}
return result.size() - add;
}
int main() {
int arr[] = {-1, 1, 2, 3, 4, 5, 6};
print(TwoNumSum(arr, int(sizeof(arr) / sizeof(int)), 5));
vector<vector<int>> ret;
NNumSum(arr, int(sizeof(arr) / sizeof(int)), 3, 6, ret);
print(ret);
return 0;
}