Finding all possible combinations of numbers to reach a given sum

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

    This is similar to a coin change problem

    public class CoinCount 
    {   
    public static void main(String[] args)
    {
        int[] coins={1,4,6,2,3,5};
        int count=0;
    
        for (int i=0;i=coins.length)
            return 0;
    
        int sumNow=curSum+coins[index];
        if (sumNow>Sum)
            return 0;
        if (sumNow==Sum)
            return 1;
    
        for (int i= index+1;i

提交回复
热议问题