您的位置:首页 > 职场人生

中兴的一道面试题

2004-12-04 13:54 411 查看
随便写写。

题目:输入两个整数 n 和 m,从数列1,2,3.......n 中 随意取几个数,
使其和等于 m ,要求将其中所有的可能组合列出来.编程求解.

#include <stdio.h>
#include <stdlib.h>

#define MAX_STACK 128

int addends[MAX_STACK] = {0};
int sp = 0;

void get_sum(int sum, int maxAddend) {
int i = 0;
int start = min(maxAddend, sum);
if (sum == 0) {
for (i=sp-1; i>0; --i)
printf("%d+", addends[i]);
printf("%d/n", addends[0]);
} else {
for (i=start; i>0; --i) {
addends[sp++] = i;
get_sum(sum-i, maxAddend);
--sp;
}
}
}

int main(int argc, char *argv[]) {
int m,n;
if (argc != 3) {
printf("Input the sum (m) and the max addend (n), with space seperated:");
scanf("%d%d", &m, &n);
} else {
m = atoi(argv[1]);
n = atoi(argv[2]);
}
if (m <=0 || n<=0 || m >= MAX_STACK) return 1;

get_sum(m, n);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: