现在的位置: 首页 > 综合 > 正文

中兴的一道面试题

2012年01月24日 ⁄ 综合 ⁄ 共 670字 ⁄ 字号 评论关闭

随便写写。

题目:输入两个整数 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;
}

抱歉!评论已关闭.