穷举算法思想

穷举算法的基本思想就是从所有可能的情况中搜索正确的答案,在使用穷举算法时,需要明确问题的答案的范围,在范围中搜索出每一种答案,得到你最想要的答案

1. 对于一种可能的情况,计算出结果

2. 判断结果是否满足,不满足就继续搜索下一个答案,满足要求则表示找到一个正确答案

 

穷举算法实例:

鸡兔同笼,共有35个头,94条腿,鸡兔各有多少只? (答案范围有两个, 小鸡假设有35只,兔子假设有35只) 看看算法的效果

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            qiongJT(35,94);


            Console.ReadKey();
        }


        static void qiongJT(int head,int foot) 
        {
            for (int i = 0, j =0; i <= head; i++)
            {
                j = head - i;

                //i * 2 = 小鸡的总脚
                //j * 4 = 兔子的总脚
                if(i * 2 + j * 4 == foot)
                {
                    Console.WriteLine("小鸡有:{0}只", i);
                    Console.WriteLine("兔子有:{0}只", j);
                    Console.WriteLine("---------------------------------");
                }

            }
        }

    }
}

效果:

image

posted @ 2015-07-25 13:08  盘子脸  阅读(577)  评论(0编辑  收藏  举报