迭代法和窮舉法

來源:互聯網
上載者:User

標籤:

迭代法:
每次迴圈都要把某一個或多個變數不斷放大,為的是下一次迴圈可以繼續使用,最後達到最終的大小。
代表性的題:
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();

運算結果

迭代法和窮舉法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.