1.枚举
枚举,也称为列举法或穷举法,是一种暴力策略的具体体现。它的核心思想是将问题的所有可能答案一一列举出来,然后根据问题的条件检验每个答案是否合适,合适的答案就保留下来,不合适的答案则丢弃。它适用于问题规模较小或没有更好算法的情况。虽然它可能不是最优的解决方案,但在某些情况下确实是一种可行的选择。
2.枚举算法的基本实施步骤
- 根据问题的具体情况确定枚举量(可以是简单变量或数组)。
- 根据问题的具体清空确定枚举范围,设置枚举循环。
- 根据问题的具体要求确定筛选(约束)条件。
- 设计枚举程序并运行、调试,对运行结果进行分析与讨论。
3.枚举算法的特点
- 得到的结果肯定是正确的,因为是通过逐一列举所有可能情况来得出的。
- 可能做了很多的无用功,因为需要遍历所有可能的情况,所以效率低下。
- 通常会涉及求最大值和最小值的问题。
4.枚举解决abc+def=ghi的问题
#include<iostream>
#include<string.h>
#define MAX 100
using namespace std;
int main(){
int a[10],book[10],total=0;
for ( a[1] = 1; a[1] <= 9; a[1]++)
for ( a[2] = 1; a[2] <= 9; a[2]++)
for ( a[3] = 1; a[3] <= 9; a[3]++)
for ( a[4] = 1; a[4] <= 9; a[4]++)
for ( a[5] = 1; a[5] <= 9; a[5]++)
for ( a[6] = 1; a[6] <= 9; a[6]++)
for ( a[7] = 1; a[7] <= 9; a[7]++)
for ( a[8] = 1; a[8] <= 9; a[8]++)
for ( a[9] = 1; a[9] <= 9; a[9]++){
for (int i = 0; i <=9; i++)book[i]=0;
for (int i = 0; i <=9; i++)book[a[i]]=1;//标记出现过的数字
int sum=0;
for (int i = 0; i <=9; i++)sum+=book[i];//计算出现过几个不同的数
if (sum==9&&a[1]*100+a[2]*10+a[3]+a[4]*100+a[5]*10+a[6]==a[7]*100+a[8]*10+a[9])
{
total++;
for (int i = 1; i <=9; i++)cout<<a[i]<<" ";
putchar(10);
}
}
cout<<"total="<<total/2;
return 0;
}
4.注意事项
思考一下为什么total/2
(因为两个数交换位置是一样)