// 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个数 取任意个数相加求和的个数
最新推荐文章于 2023-08-23 20:32:18 发布
本文介绍了一个经典的背包问题求解方法,通过使用C++实现了一种有效的算法来计算从给定的整数数组中选取元素相加能得到多少种不同的结果。特别强调了在处理这类问题时避免陷入死循环和越界的技巧。

651

被折叠的 条评论
为什么被折叠?



