标题:李白打酒

/*
话说大诗人李白,一生好饮。幸好他从不开车。

一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:

无事街上走,提壶去打酒。
逢店加一倍,遇花喝一斗。

这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。 

请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。
像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。

注意:通过浏览器提交答案。答案是个整数。不要书写任何多余的内容。
该题型为排列组合问题
 */
public class demo7 {
    static int sum = 0;
    static char c[] = new char[16];

    public static void main(String[] args) {
//        c[15] = '\0';
//        fun1(2, 1, 0, 0);
        fun2(5, 9, 2);// 遇店a,遇花b,斗酒c(为何b=9?由于最后一次是遇花,不用考虑在内,否则要排除不是遇花的情况)
        System.out.println(sum);
    }

    // now为当前酒的斗数,count为总的遇见的次数,d为店的数目,h为花的数目。
    public static void fun1(int now, int n, int d, int h) {// 方法1
        if (now < 0 || n > 16 || (now == 0 && n < 16)) {
            return;// 满足条件返回
        }
        if (now == 0) {
            if (n == 16 && d == 5 && h == 10) {// 满足次数加1
                sum++;
                System.out.print("sum:" + sum + "  ");
                System.out.println(c);// 输出字符串
            }
        }
        c[n - 1] = 'a';// 第一次为店的情况
        fun1(now * 2, n + 1, d + 1, h);
        c[n - 1] = 'b';// 第一次为花的情况
        fun1(now - 1, n + 1, d, h + 1);
    }

    public static void fun2(int a, int b, int c) {// 方法2,偏难
        if (a > 0)
            fun2(a - 1, b, c * 2); // 递归调用,a==0执行下一步
        if (b > 0)
            fun2(a, b - 1, c - 1); // 递归调用,b==0执行下一步
        if (a == 0 && b == 0 && c == 1) // c==1,由于最后一次是遇花,还未减去1,此时判断的结果刚好是李白喝完酒了
            sum += 1;
    }
}

output:14

烧脑袋......

猜你喜欢

转载自www.cnblogs.com/hardhp74520/p/11741037.html
今日推荐