Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3143
一个人的身影
一个人的身影 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:06

    C++ version of the same algorithm

    #include 
    #include 
    void subset_sum_recursive(std::list numbers, int target, std::list partial)
    {
            int s = 0;
            for (std::list::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
            {
                s += *cit;
            }
            if(s == target)
            {
                    std::cout << "sum([";
    
                    for (std::list::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
                    {
                        std::cout << *cit << ",";
                    }
                    std::cout << "])=" << target << std::endl;
            }
            if(s >= target)
                return;
            int n;
            for (std::list::const_iterator ai = numbers.begin(); ai != numbers.end(); ai++)
            {
                n = *ai;
                std::list remaining;
                for(std::list::const_iterator aj = ai; aj != numbers.end(); aj++)
                {
                    if(aj == ai)continue;
                    remaining.push_back(*aj);
                }
                std::list partial_rec=partial;
                partial_rec.push_back(n);
                subset_sum_recursive(remaining,target,partial_rec);
    
            }
    }
    
    void subset_sum(std::list numbers,int target)
    {
        subset_sum_recursive(numbers,target,std::list());
    }
    int main()
    {
        std::list a;
        a.push_back (3); a.push_back (9); a.push_back (8);
        a.push_back (4);
        a.push_back (5);
        a.push_back (7);
        a.push_back (10);
        int n = 15;
        //std::cin >> n;
        subset_sum(a, n);
        return 0;
    }
    

提交回复
热议问题