核工业计算机应用研究所笔试题。

1元,5元,10元的人民币,组合成100元
使用《组合数学》里面的生成函数的方式实现(生成函数很暴力,生成函数的具体内容非常复杂):
假设1*x + 5*y + 10*z == 100
x , y , z 的取值范围为 : x = [0,100]  y = [0,20]  z = [0,10]
public class CombinationTest
{
    public static void main(String[] args)
    {
        int count = 0;
        
        int time = 0;
        
        for(int x = 0;x <= 100;x++)
        {
            for(int y = 0;y <= 20;y++)
            {
                for(int z = 0;z <= 10;z++)
                {
                    if(1*x + 5*y + 10*z == 100)
                    {
                        count++;
                    }
                    time++;
                }
            }
        }
        System.out.println("循环的次数有:" + time + "次");
        
        System.out.println("组合的方式有:" + count + "种");
    }
}
使用动态规划更合适!

这样循环次数更少(效率更高!):

public class DynamicPlanningTest
{
    static int[] values = {1,5,10};
    
    static int count = 0;
    
    static int time = 0;

    public static void main(String[] args)
    {
        split(100, 0, "");
        
        System.out.println("循环的次数有:" + time + "次");
        
        System.out.println("组合的方式有:" + count + "种");
    }

    public static void split(int x, int y, String z)
    {
        if (x < 0)
        {
            return;
        }else
        if (x == 0)
        {
            System.out.println(z);
            
            count++;
            
            return;
        }else
        for (int i = y; i < values.length; i++)
        {
            split(x - values[i],i,z + values[i] + "|");
            
            time++;
        }
    }
}

原文地址:https://www.cnblogs.com/javacatalina/p/6664108.html