n个数 取任意个数相加求和的个数

44 篇文章 0 订阅
17 篇文章 0 订阅
// 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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值