基本思想:
从所有可能的情况中搜索正确答案;
执行步骤:
1、对于一种可能的情况,计算其结果;
2、判断结果是否满足要求,如果不满足,继续执行第一步来搜索正确答案;如果满足,则找到了一个正确答案;
穷举法效率并不高,适合于一些没有明显规律可循的场合,在使用穷举法时,需要明确问题的答案的范围,这样才可以在指定范围内搜索答案,指定范围之后就可以使用循环语句和条件判断语句逐步验证候选答案的正确性,从而得到需要的正确的答案;
实例:
鸡兔同笼,有35头,94足,求鸡兔各多少只?
/**
* @ClassName TestDemo8
* @Description 穷举法
* @Author lzq
* @Date 2018/11/29 21:13
* @Version 1.0
**/
public class TestDemo8 {
public static void main(String[] args) {
System.out.println("鸡:"+method_of_exhaustion(35,94)[0]+"\t兔:"+
method_of_exhaustion(35,94)[1]);
}
public static int[] method_of_exhaustion(int head,int foot) {
int i,j;
for(i = 0;i <= head;i++) {
j = head-i;
if(i*2+j*4 == foot) {
return new int[] {i,j};
}
}
return new int[] {-1,-1}; //无解
}
}
鸡:23 兔:12