【算法】啤酒與瓶蓋與空瓶(java)

題目描述:
啤酒2元一瓶 4個瓶蓋能換1瓶啤酒,2個空瓶也能換1瓶啤酒,問:n元錢最多能喝幾瓶酒?
解題思路:
在不能借瓶蓋的狀況下,第一種方法直接暴力求解。code

/* 啤酒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);
  }
}
相關文章
相關標籤/搜索