题目描述:
啤酒2元一瓶 4个瓶盖能换1瓶啤酒,2个空瓶也能换1瓶啤酒,问:n元钱最多能喝几瓶酒?
解题思路:
在不能借瓶盖的情况下,第一种方法直接暴力求解。
/* 啤酒2元一瓶 4个瓶盖能换1瓶啤酒,2个空瓶也能换1瓶啤酒*/
/*n元钱最多能喝几瓶酒?*/
public class ForTest {
static class Solution {
public int canDrink(int money) {
int beer_num=0;
int lid_num=0;
int bottle_num=0;
int ans=0;
while ((money>0&&money%2==0)||lid_num>=4||bottle_num>=2){
if(money>0&&money%2==0){
beer_num=money/2;
lid_num=beer_num;
bottle_num=beer_num;
money-=2*beer_num;
ans+=beer_num;
}
if(lid_num>=4){
beer_num=lid_num/4;
lid_num=lid_num-beer_num*4+beer_num;
bottle_num+=beer_num;
ans+=beer_num;
}
if(bottle_num>=2){
beer_num=bottle_num/2;
lid_num+=beer_num;
bottle_num=bottle_num-beer_num*2+beer_num;
ans+=beer_num;
}
}
return ans;
}
}
public static void main(String[] args) {
Solution s=new Solution();
int ans=s.canDrink(10);
System.out.println(ans);
}
}
第二种方法用递归求解。
/* 啤酒2元一瓶 4个瓶盖能换1瓶啤酒,2个空瓶也能换1瓶啤酒*/
/*n元钱最多能喝几瓶酒?*/
public class ForTest {
static class Solution {
public int canDrink(int money, int lib_num, int bottle_num,int ans) {
if ((money <= 0 || money == 1) && lib_num < 4 && bottle_num < 2) {
return ans;
}else {
if (money > 0&&money!=1) {
ans++;
return canDrink(money - 2, lib_num + 1, bottle_num + 1,ans);
}
if (lib_num >= 4) {
ans++;
return canDrink(money, lib_num - 4 + 1, bottle_num + 1,ans);
}
if (bottle_num >= 2) {
ans++;
return canDrink(money, lib_num + 1, bottle_num - 2 + 1,ans);
}
return ans;
}
}
}
public static void main(String[] args) {
Solution s = new Solution();
int ans=s.canDrink(10, 0, 0,0);
System.out.println(ans);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。