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;
            }



  • 相关阅读:
    从零开始入门 K8s | 应用编排与管理
    209. Minimum Size Subarray Sum
    208. Implement Trie (Prefix Tree)
    207. Course Schedule
    203. Remove Linked List Elements
    183. Customers Who Never Order
    182. Duplicate Emails
    181. Employees Earning More Than Their Managers
    1261. Find Elements in a Contaminated Binary Tree
    1260. Shift 2D Grid
  • 原文地址:https://www.cnblogs.com/tao-zi/p/3832573.html
Copyright © 2011-2022 走看看