李白打酒问题

李白打酒问题

题目描述
李白打酒

  • 一天李白提着酒出来,酒壶中有酒2斗,他边走边唱:
  • 无事街上走,提壶去打酒,逢店加一倍,遇花喝一抖.
  • 一共遇见店5次,花10次,最后遇到花,刚好把酒喝光
  • 计算可能的方案

思路解析

两斗酒,看到店了酒*2,看到花了酒-1,最后看到花刚好喝完酒
一共看到5次店10次花
计算方案数量
这题是典型的搜索问题,
结束条件是看完了店,还剩一次花,酒剩一斗.
题目简化为5次店,10次花,最后剩一斗酒一次花的搜索问题

代码如下

 private static int  count;
	private static void countresult(int store,int flowers,int wine) {
    
    
		if(store==0&&flowers==1&&wine==1) count++;
		if(store>0)countresult(store-1,flowers,wine*2);
		if(flowers>0)countresult(store,flowers-1,wine-1);
		
	}
	public static void main(String[] args) {
    
    
		countresult(5,10,2);
		System.out.println(count);
	}

坑位提醒
这里我第一次做的时候把花的初始值设为9,酒初始值设为1,判断改成wine=0,flowers=0;
花是做加减运算不会影响结果,而酒是做乘法运算,乘法运算会影响最终结果.

最后得到结果14

猜你喜欢

转载自blog.csdn.net/qq_45657198/article/details/112514312