C++问题(统计和的个数)

来源:百度知道 编辑:UC知道 时间:2024/05/23 11:23:14
输入五个整数(总和不大于10000),任其中1个或多个相加,问可得多少个不同的数字?
请高手指点下,用什么思路来做这道题?

用循环
for (i=0;i<5;i++)
for (j=i;j<5;j++)
{
s++;
}
0--->0,1,2,3,4
1--->1,2,3,4
2--->2,3,4
3--->3,4
4--->4

先定义5个数,用户输入后判断是否《10000 然后用循环,使任意两个相加,3个相加,4个相加,判断他们的结果是否相等不等的话N+1 最后n就是结果数

嵌套循环或者回溯。
反正只有5个整数,嵌套5个循环问题不大。
用回溯代码会短很多。我给一个回溯的。
#include<iostream>

using namespace std;

int stack[10000]; //用来存储不同的和的栈
int top = 0; //栈顶

void Fun(const int a[], int max, int n, int & s);
void Insert(int s);

int main()
{
const int MAX = 5;
int a[MAX] = {0};
for (int i=0; i<MAX; i++)
cin >> a[i];
for (int i=0; i<MAX; i++)
cout << a[i] << " ";
cout << endl;

int s = 0;
Fun(a, MAX, 0, s);
cout << top << endl;

system("pause");
return 0;
}