// MicroSofrInterviewProblem2.cpp : Defines the entry point for the console application.
//有若干个给定的数(都小于N),问从中任意取几个数相加,可以得到多少个不同的结果.
//处理这种类似背包的时候,注意内层循环一定要memcpy重建一个副本,不然会陷入死循环并越界。如题,j = 0, 当0 + 1记录在record[1],下一次record[1]也是1了就那么reocrd[2]也会赋值为1,直到循环结束,这样程序就挂了。
//类似的一共有多少种可能性的问题,都会出现类似的问题。需要注意。
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#define MAX 100
int poscount(int* input, int len) {
if (input == NULL || len == 0) return 0;
int count = 1;
char record[MAX] = { 0 };
record[0] = 1;
printf("0 ");
int i = 0;
for (; i<len; i++) {
int j;
char tmp[MAX];
memcpy(tmp, record, MAX);
for (j = 0; j<MAX; j++) {
if ((record[j] == 1) && (record[j + input[i]] == 0)) {
tmp[j + input[i]] = 1;
printf("%d ", j + input[i]);
count++;
}
}
memcpy(record, tmp, MAX);
}
printf("\ncount = %d \n", count);
return count;
}
int main() {
int input[] = { 1,2,3,5 };
poscount(input, sizeof(input) / sizeof(int));
while (1);
}
n个数 取任意个数相加求和的个数
最新推荐文章于 2024-03-15 22:42:32 发布