问题描述: 有 三个 盒子,每个盒子内有若干个球,两个人轮流取,每人每次只能从一个盒子内取至少一个球,取到最后一个球的人输。
比如3,4,5的话,先手通过特定的步骤能够获胜。
问题分析:没有找到必胜的潜在规律,因此,编写遍历所有情况,以判断先手是否必胜。这是一个递归调用的问题,因此需要设置递归的结束条件。
通过树汇总所有的情况,然后将可以胜利的每个步骤都打印出来。
具体的代码如下:
package game; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class howWin { private int BOX_NUM = 0; private int[] BoxList = null; private treeNode travelTree; private List<treeNode> YesNode = new ArrayList<treeNode>(); private List<treeNode> otherFixedFailState = new ArrayList<treeNode>(); public class treeNode { public List<treeNode> childs; public String nodeInfo; public treeNode father; public treeNode(String info){ nodeInfo = info; childs = new ArrayList(); childs.clear(); } public void addNode(treeNode tree) { childs.add(tree); tree.father = this; } } public howWin(){ } public void setBoxBallNum(int[] boxSum){ BoxList = boxSum; BOX_NUM = BoxList.length; travelTree = new treeNode("Root" + genListInfo(BoxList)); }