# 1-5、算法设计常用思想之穷举法

• 确定问题的解（或状态）的定义、解空间的范围以及正确解的判定条件；
• 根据解空间的特点来选择搜索策略，逐个检验解空间中的候选解是否正确；

void Buy()
{
int count = 0;

for (int roosters = 0; roosters <= 20; roosters++)   //枚举大公鸡数量
{
for (int hens = 0; hens <= 33; hens++) //枚举母鸡数量
{
int chicks = 100 - roosters - hens;  //剩下的就是小鸡数量
if (((chicks % 3) == 0) //小鸡个数应该是 3 的整数倍，算是个小小的剪枝
&& ((5 * roosters + 3 * hens + chicks / 3) == 100)) //是否凑够 100 钱
{
count++;
std::cout << "买法 " << count << "：公鸡 " << roosters
<< ", 母鸡 " << hens
<< ", 小鸡 " << chicks << std::endl;
}
}
}

std::cout << "共有 " << count << " 种买法" << std::endl;
}
-- lua实现
function bug()
local count = 0
for roosters = 0, 20 do
for hens = 0, 33 do
local chicks = 100 - roosters - hens
if (((chicks % 3) == 0) and ((5 * roosters + 3 * hens + chicks / 3) == 100)) then
count = count + 1
print("====买法", count, roosters, hens, chicks)
end
end
end
print("====共有买法", count)
end

for ji = 1, 50 do
local tu = 50 - ji
if (tu * 4 + ji * 2) == 120 then
print("===========鸡 兔各", ji, tu)
break
end
end

posted @ 2019-05-29 23:44  orxx  阅读(1995)  评论(0编辑  收藏  举报