24点问题:收取四张牌加起来等于24点的可能有哪些?
/**
*
* @author 陈鑫
* 回溯解决24点问题
*
*/
public class TwentyFourPoints {
public static void scratchCard(ArrayList<Integer> cardList,ArrayList<Integer> handList) {
int length = handList.size();//手牌数量
Integer count = 0;//总点数
//计算手牌总点数
if(length != 0 || length < 5) {
for(Integer card:handList) {
count += card;
}
}
//当手牌数量小于4或者手牌总点数大于等于24时抓牌
if(count < 24 && length < 4) {
for(Integer card : cardList){
//重新定义handList
ArrayList<Integer> newHandList = new ArrayList<Integer>();
//添加手牌
newHandList.addAll(handList);
newHandList.add(card);
//注意:方法传参传的是ArrayList的对象的引用地址,会导致原有的List集合会重复添加
//递归抓牌
scratchCard(cardList,newHandList);
}
}else if(count == 24 && length == 4) {
//当手牌数量等于4并且总点数等于24点的时候打印
for(Integer cardPrint:handList) {
System.out.print(cardPrint + ",");
}
System.out.println();
}
}
public static void main(String[] args) {
//牌堆
ArrayList<Integer> cardList = new ArrayList<Integer>();
//牌堆初始化
for(int i=1;i<11;i++) {
cardList.add(i);
}
//手牌
ArrayList<Integer> handList = new ArrayList<Integer>();
//抓牌
scratchCard(cardList,handList);
}
}