李白打酒
问题描述
话说大诗人李白,一生好饮。幸好他从不开车。
一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:
无事街上走,提壶去打酒。逢店加一倍,遇花喝一斗。
这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。
请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?
思路
因为他总共遇到花10次,遇到店5次,如果按照ab这样的来排序的话,总共就是十五个ab
那么按照排列组合来说 就是二的十五次方,(2^15)
所以,现在最大的问题就是怎么将这些数按照规定的样子进行自由组合?
首先想到的就是用二进制数0 1来进行组合到最后再用Java中的repalce方法来转换为ab
那么怎么进行排列呢?
我们这样想:
十进制数
0~2^14
二进制数
0~100000000000000
那么显而易见,只要在这二进制数中找到符合规定的就行,最后用代码实现
代码实现
public class solution {
public static void main(String[] args) {
String temp = "";
String temp2 = "";
int count = 0 ;
for(int i = 0 ; i < Math.pow(2, 14) ; i++) {
temp = Integer.toBinaryString(i);
temp2 = temp.replace("0", "");
if(temp2.length() == 5) {
temp += 0 ;
if(temp.length() < 15) {
for(int j = temp.length() ; j < 15 ; j++) {
temp = "0" + temp;
}
}
if(meth(temp.toCharArray())) {
count++;
}
}
}
System.out.println("共有"+ count +"方案");
}
public static boolean meth(char[] DH) {
int jiu = 2;
for(int i = 0 ; i < DH.length ; i++) {
if(DH[i] == '0') {
jiu--;
}else {
jiu *= 2;
}
}
if(jiu == 0) {
String a = String.copyValueOf(DH);
a = a.replace("1","a");
a = a.replace("0", "b");
System.out.println(a);
return true;
}
return false;
}
}