# 高手们帮小弟我一下.A+B+C+D+E+F=120的程序

www.myexceptions.net  网友分享于：2013-12-21  浏览：9次

abcdef的值为1-100之间

a+b+c+d+e+f=10
1+2+1+1+1+4=10
2+2+2+2+1+1=10
........

------解决方案--------------------
class Program
{
static void Main(string[] args)
{
Combine(120, 5);
}
static void Combine(int sum, int numCount)
{
int[] pos = new int[numCount];
for (int i = 0; i < pos.Length; i++)
{
pos[i] = i + 1;
}
int curNum = numCount - 1;
while (pos[0] <= sum - numCount)
{
if (pos[curNum] <= sum - (numCount - curNum))
{
PrintArr(sum, pos);
pos[curNum]++;
}
else
{
curNum--;
if (curNum < 0)
{
break;
}
}
}
}
static void PrintArr(int sum, int[] pos)
{
for (int i = 0; i < pos.Length ; i++)
{

if (i == pos.Length - 1)
{
Console.Write(sum - pos[i]);
Console.WriteLine();
}
else if (i == 0)
{
Console.Write(pos[i] - 0+ "+ ");
}
else
{
Console.Write(pos[i + 1] - pos[i] + "+ ");
}
}
}
}
------解决方案--------------------

#include <iostream>
using namespace std;
#define COUNT 6
#define RESULT 120
int save[COUNT+1];
void fun(int nCount,int nStart,int nTotal)
{
if(nCount==1)
{
save[nCount]=nTotal;///
for(int i=COUNT;i> 1;i--)///
cout < <save[i] < < "+ ";///
cout < <save[1] < < "= " < <RESULT < <endl;///
return;
}
for(int i=nStart;i <=nTotal/nCount;i++)
{
save[nCount]=i;///
fun(nCount-1,i,nTotal-i);
}
}
void main()
{
fun(COUNT,1,RESULT);
}
------解决方案--------------------
sorry,上面的程序没有加入 {A,B,C,D,E,F} <100的限制,改下,并加入统计结果数目功能
#include <iostream>
using namespace std;

#define MIN(a,b) (a <b?a:b)
#define COUNT 6
#define RESULT 120
#define MIN_ 1
#define MAX_ 100
int save[COUNT+1];
int nCountResult; //统计得到结果的数目

void fun(int nCount,int nMin,int nMax,int nTotal)
{
if(nCount==1)
{
if(nTotal <=nMax)
{
save[nCount]=nTotal;
for(int i=COUNT;i> 1;i--)
cout < <save[i] < < "+ ";
cout < <save[1] < < "= " < <RESULT < <endl;
nCountResult++;
}