题目:输入两个整数n和m,从数列1,2,3.....n中随意曲几个数,使其和等于m,要求将其中所有的可能组合列出来。
答:
#include "stdafx.h" #include <iostream> #include<list> using namespace std; //1到N中所有和为M的组合 void FindAllCombinationEqualM(list<int> &l, int m, int n) { if (m <= 0 || n <= 0) { return; } if (m == n) { for (list<int>::iterator iter = l.begin(); iter != l.end(); iter++) { cout<<*iter<<" + "; } cout<<n<<endl; } l.push_back(n); FindAllCombinationEqualM(l, m - n, n - 1); l.pop_back(); FindAllCombinationEqualM(l, m, n - 1); } int _tmain(int argc, _TCHAR* argv[]) { int n; int m; cout<<"1到N中所有和为M的组合, 输入n和m:"; cin>>n>>m; list<int> l; FindAllCombinationEqualM(l, m, n); cout<<endl; return 0; }
运行界面如下: