Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3091
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  醉酒成梦
    2020-11-21 07:18

    Very efficient algorithm using tables i wrote in c++ couple a years ago.

    If you set PRINT 1 it will print all combinations(but it wont be use the efficient method).

    Its so efficient that it calculate more than 10^14 combinations in less than 10ms.

    #include 
    #include 
    //#include "CTime.h"
    
    #define SUM 300
    #define MAXNUMsSIZE 30
    
    #define PRINT 0
    
    
    long long CountAddToSum(int,int[],int,const int[],int);
    void printr(const int[], int);
    long long table1[SUM][MAXNUMsSIZE];
    
    int main()
    {
        int Nums[]={3,4,5,6,7,9,13,11,12,13,22,35,17,14,18,23,33,54};
        int sum=SUM;
        int size=sizeof(Nums)/sizeof(int);
        int i,j,a[]={0};
        long long N=0;
        //CTime timer1;
    
        for(i=0;i0 && PRINT==0) return table1[s][arrsize];
        if(s==0)
        {
            if(PRINT) printr(r, rsize);
            return 1;
        }
        if(arrsize==0) return 0;
    
        //else
        rnew=(int*)malloc((rsize+1)*sizeof(int));
    
        for(i=0;i

提交回复
热议问题