方法1:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<vector> #include <algorithm> #include<iostream> using namespace std; void getResult(vector<int> a,int result) { sort(a.begin(),a.end()); int nLen = a.size(); for (int i = 0; i < nLen; i++) { if (a[i] == result) cout<<a[i]<<endl; for (int j = i + 1; j < nLen; j++) { if (a[i] + a[j] > result) break; if (a[i] + a[j] == result) { cout<<a[i]<<"+"<<a[j]<<endl; } else { for (int k = j + 1; k < nLen; k++) { if (a[i] + a[j] + a[k] > result) break; if (a[i] + a[j] + a[k] == result) { cout<< a[i]<< "+"<<a[j]<<"+"<<a[k]<<endl; } else { for (int l = k + 1; l < nLen; l++) { if (a[i] + a[j] + a[k] + a[l] > result) break; if (a[i] + a[j] + a[k] + a[l] == result) cout<<a[i]<<"+"<< a[j]<< "+" <<a[k]<<"+"<<a[l]<<endl; //else继续,有点复杂。 } } } } } } } void main() { vector<int> a; a.push_back(11); a.push_back(2); a.push_back(3); a.push_back(1); a.push_back(4); a.push_back(10); a.push_back(23); a.push_back(7); a.push_back(8); a.push_back(9); a.push_back(6); a.push_back(12); getResult(a,10); system("pause"); }
#include <list> #include <vector> using namespace std; typedef vector<double> ListD; typedef vector<ListD> ListLD; // 给定一个数字数组,从这个数组中找出所有的组合,使组合中各数字相加等于一个给定数值 // nums = 给定数组 // num = 给定数值 // index = 当前操作的数字在数组中的index // count = 存储所有组合的可能数 // results = 存储所有组合的情况 void NumCount(double nums[], double num, int index, int &count, ListLD &results,int NumLen) { //当前操作的数字=给定数值 if (nums[index] == num) { //保存此组合 results[results.size() - 1].push_back(nums[index]); count += 1; //清空缓存并将除了此数之外的此组合的另外的数字存入缓存里 ListD TmpList; results.push_back(TmpList); for (int i = 0; i < results[results.size() - 2].size() - 1; i++) { results[results.size() - 1].push_back(results[results.size() - 2][i]); } if (index == - 1) { return; } //进入到下一递归 NumCount(nums, num, index + 1, count, results,NumLen); } //大于给定数,跳过此数,进入到下一次递归 else if (nums[index] > num) { if (index == NumLen - 1) { return; } //此组合无效,跳到下一递归 NumCount(nums, num, index + 1, count, results,NumLen); } //小于给定数,则保存此数至缓存之后,给定数减去此数,然后进入下一次递归,之后将此数从缓存中删除 else { if (index == NumLen - 1) { return; } results[results.size() - 1].push_back(nums[index]); //给定数减去此数 int tempNum = num - nums[index]; //进入到下一递归 NumCount(nums, tempNum, index + 1, count, results,NumLen); //将此数从缓存中删除 ListD::iterator itr= results[results.size() - 1].begin(); itr+=(results[results.size() - 1].size() - 1); results[results.size() - 1].erase(itr); if (index < NumLen - 1) { //再跳过过此数,给定数不变,进入到下一次递归 NumCount(nums, num, index + 1,count,results,NumLen); } } } int main() { double test[10] = {1,2,3,4,5,6,7,8,9,10}; ListLD testList; int a = 0,b=0; NumCount(test,10,a,b,testList,10); return 0; }
此代码运行出错,我根据C#翻译的,原文地址