• 迭代法和穷举法


    迭代法:
    每次循环都要把某一个或多个变量不断放大,为的是下一次循环可以继续使用,最后达到最终的大小。
    代表性的题:
    1、累加求和
    2、阶乘
    3、折纸
    int sum = 0;
    for(int i=1;i<=10;i++)
    {
      sum += i;
    }

    穷举法:
    将所有的可能性都走一遍,然后判断符合条件的可能性,单独拿出来。
    基本用法:
    int count = 0;
    for (int i = 1; i <= 15; i++) //1分的硬币
    {
      for (int j = 1; j <= 7; j++)//2分的硬币
      {
        for (int u = 1; u <= 3; u++) //5分的硬币
        {
          if (i + (j * 2) + (u * 5) == 15) //****
          {
            Console.WriteLine("1分的需要" + i + "个,2分的需要" + j + "个,5分的需要" + u + "个");
            count++;
          }
        }
      }
    }

    Console.WriteLine("总共有" + count + "种可能性!");

    练习1

    百鸡百钱,有100文钱,要买100只鸡回家。公鸡2文钱一只,母鸡1文钱一只,小鸡半文钱一只,该如何买?

                int count = 0;//次数
                for (int i = 0; i <= 200; i++)//小鸡
                {
                    for (int j = 0; j <= 100; j++)//母鸡
                    {
                        for (int u = 0; u <= 50; u++)//公鸡
                        {
                            if ((i * 0.5) + j + (u * 2) == 100)
                            {
                                if (i+j+u==100)
                                {
                                    Console.WriteLine("公鸡" + u + "只,母鸡" + j + "只,小鸡" + i + "只。");
                                    count++;
                                }
                            }
                        }
                    }
                }
                Console.WriteLine(count );
                    Console.ReadLine();            

    运算结果

    练习2

    有三种硬币若干个,1分,2分,5分,如果要凑够1毛5,有哪些组合方式?
    扩展:三种硬币最少都要有一个

                int count = 0;
                for (int i = 1; i <= 15; i++)
                {
                    for (int j = 1; j <= 7; j++)
                    {
                        for (int a = 1; a <= 3; a++)
                        {
                            if (i + (j * 2) + (a * 5) == 15)
                            {
                                Console.WriteLine("1分需要" + i + "个,2分需要" + j + "个,5分需要" + a + "");
                                count++;
                            }
                        }
                    }
                }
                Console.WriteLine(count);
                Console.ReadLine();

    运算结果

  • 相关阅读:
    最短路
    Codeforces Round #607 (Div. 2) C. Cut and Paste
    第三次训练赛
    训练赛
    day27-反射
    day26-网络编程
    tcp文件上传--多个客户端
    tcp图片上传
    tcp文件上传优化
    tcp文件上传
  • 原文地址:https://www.cnblogs.com/sunshuping/p/5524522.html
Copyright © 2020-2023  润新知