数组的组合问题 新手求救
三个数组 数组1 {1,2,3,4,5};
数组1 {3,4,5};
数组1 {2,3,5};
求怎么算出来 三个数组组合的和,输出大于10小于15的组合;
比如 {2,4,5},{3,3,5},{4,4,3}.。。。 感觉好多啊。。。
有点晕。。。 在线等前辈回答 谢谢!
[解决办法]
三个循环嵌套就好了,下面是伪代码
for (int i = 0; i< size; i++) for(int j = 0; j< size2; j++) for (int k = 0; k < size3; k++) { int iSum = a[i] + b[j] + c[k]; if (iSum > 10 && iSum <15) cout<<{a[i], b[j], c[k]} ; }
[解决办法]
#include <iostream>using namespace std;// written by cc_teamvoid printSumIsSth(const vector<int *> &arrPointerArr, const vector<int> &arrElementCount, vector<int> &arrElementCanChosenCount, vector<int> &arrElementChosenIndex, unsigned min, unsigned max){ for(int i = 0; i < arrElementCanChosenCount.size(); ++i) { if(arrElementCanChosenCount[i] > 0) { for(int j = 0; j < arrElementCount[i]; ++j) { arrElementChosenIndex[i] = j; arrElementCanChosenCount[i]--; printSumIsSth(arrPointerArr, arrElementCount, arrElementCanChosenCount, arrElementChosenIndex, min, max); arrElementCanChosenCount[i]++; } return; } } int tempSum = 0; for(int i = 0; i < arrPointerArr.size(); ++i) { tempSum += arrPointerArr[i][arrElementChosenIndex[i]]; } if(tempSum >= min && tempSum <= max) { for(int j = 0; j < arrPointerArr.size(); ++j) { cout << arrPointerArr[j][arrElementChosenIndex[j]]; } cout << endl; }}int main(){#if 1 // printSumIsSth int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {3, 4, 5}; int arr3[] = {2, 3, 5}; vector<int *> arrPointerArr; arrPointerArr.push_back(arr1); arrPointerArr.push_back(arr2); arrPointerArr.push_back(arr3); vector<int> arrElementCount; arrElementCount.push_back(sizeof(arr1) / sizeof(int)); arrElementCount.push_back(sizeof(arr2) / sizeof(int)); arrElementCount.push_back(sizeof(arr3) / sizeof(int)); vector<int> arrElementCanChosenCount(3, 1); vector<int> arrElementChosenIndex(0, 3); unsigned min = 11; unsigned max = 14; printSumIsSth(arrPointerArr, arrElementCount, arrElementCanChosenCount, arrElementChosenIndex, min, max); #endif return 0;}