zoukankan      html  css  js  c++  java
  • 求组合数的个数

    需求:求出用1、2、5这三个数的不同个数组合的和为100的组合个数。如100个1是一个组合,5个1加19个5是一个组合等等。

    分析:很明显1、2、5本身这三个数无论怎么加都无法达到100,必须用多个1,多个2,多个5才能加到100;那么到底需要用多少个1,多少个2,多个5呢?

             我们设1、2、5 这三个数的个数分别为x、y、z 即x* 1 + y* 2 +z* 5=100 !

    CSharp实现代码:

    namespace DemoC
    {
        class Program
        {
            //定义静态计算函数
            public static int CountC()
            {
                int number = 0;   //初始化计数器
                int x, y, z; 
                //设置循环条件
                for (x = 0; x <= 100; x++)
                    for (y = 0; y <= 50; y++)
                        for (z = 0; z <= 20; z++)
                            if (x * 1 + y * 2 + z * 5 == 100)
                                number++;
                return number;
            }
            static void Main(string[] args)
            {
                int cNumber = CountC();
                Console.WriteLine("满足条件的组合个数为 {0}", cNumber);
                Console.ReadKey();
            }
        }
    }

    输出结果:541

    上面的方法,CountC()函数一共要计算100*50*20次,效率非常低下;另一种解法是因为x*1+y*2+z*5=100,所以得到x*1+y*2=100-z*5

    又因为z<=20,x<=100,y<=50

    优化后的代码:

     public static int CountC()
            {
                int number = 0;   //初始化计数器
                for (int m = 0; m <= 100; m += 5)
                    number += (m + 2) / 2;
                return number;
            }



  • 相关阅读:
    六、TreeSet中的定制排序
    五、Set接口
    四、List接口
    Vocabulary Recitation 2020/05/20
    Vocabulary Recitation 2020/05/19
    Vocabulary Recitation 2020/05/18
    自控力_第六章
    Vocabulary Recitation 2020/05/17
    Vocabulary Recitation 2020/05/15
    Vocabulary Recitation 2020/05/14
  • 原文地址:https://www.cnblogs.com/tao-zi/p/3832573.html
Copyright © 2011-2022 走看看