首页 > 代码库 > 编程中穷举法的运用

编程中穷举法的运用

1·一共有200元钱,拍子15元一个,水2元一瓶,球3元一个,问每种至少买一个总共有几种可能?

            int he = 0;      //总计的可能数(从零开始)
            for (int i = 1; i * 15 <= 200; i++)    //i为拍子的个数
            {
                for (int j = 1; j * 2 <= 200; j++)  //j为水的瓶数
                {
                    for (int h = 1; h * 3 <= 200; h++)   //h为球的个数
                    {
                        if (15 * i + 2 * j + 3 * h == 200)
                        {
                            Console.WriteLine("拍子为:" + i + "、水为:" + j + "、球为:" + h);
                            he++;
                        }
                    }
                }
            }
            Console.WriteLine("一共有{0}可能", he);
            Console.ReadLine();

2·公鸡2文,母鸡1文,小鸡半文,每种至少买一只,100文钱买一百只鸡,求所有可能

            int he = 0;
            for (int i = 1; i * 2 <= 100; i++)    //i为公鸡
            {
                for (int j = 1; j <= 100; j++)     //j为母鸡
                {
                    for (int h = 1; h * 0.5 <= 100; h++)     //h为小鸡
                    {
                        if (i * 2 + j + h * 0.5 == 100 && i + j + h == 100)  //同时满足一百文钱和一百只鸡
                        {
                            Console.WriteLine("公鸡{0}只、母鸡{1}只、小鸡{2}只", i, j, h);
                            he++;
                        }
                    }
                }
            }
            Console.WriteLine("一共有{0}种可能", he);
            Console.ReadKey();

编程中穷举法的运用