打靶打10次,打中90环的可能性有多少?
用回溯法实现:
控制台输出:
递归实现:打10次90环的可能性:92378种
迭代实现:打10次90环的可能性:92378种
package AlgorithmTest; import java.util.Stack; /** * Created by dell on 2016/12/18. */ public class ShootingProblem { public static void main(String[] args) { ShootingProblemTree shootingProblemTree = new ShootingProblemTree(10, 90);//打10次要求90环 ShootingProblemTree shootingProblemTree1 = new ShootingProblemTree(10, 90); System.out.println("递归实现:打10次90环的可能性:" + shootingProblemTree.getSum() + "种"); System.out.println("迭代实现:打10次90环的可能性:" + shootingProblemTree1.getSumIteration() + "种"); } //每一次有0换到10换,11种可能性 private static class ShootingProblemTree{ private int count; private int circles; private int sum; public ShootingProblemTree(int count, int circles) { this.count = count; this.circles = circles; } private int getSum(){ solve(0, 0, -1); return this.sum; } private int getSumIteration(){ solveIteration(0, 0, -1); return this.sum; } private static class Three{ private int node; private int sum; private int nodes; public Three(int node, int sum, int nodes) { this.node = node; this.sum = sum; this.nodes = nodes; } } private void solveIteration(int node, int sum, int nodes){ Stack<Three> threes = new Stack<Three>(); threes.push(new Three(node, sum, nodes)); while (!threes.isEmpty()){ Three three = threes.pop(); node = three.node; sum = three.sum; nodes = three.nodes; if (sum + node <= this.circles && sum + node + (this.count - nodes - 1)*10 >= this.circles){ if (nodes + 1 < this.count){ for (int i = 10; i >= 0; i--){ threes.push(new Three(i, sum + node, nodes + 1)); } }else{ if (sum + node == this.circles){ this.sum++; } } } } } private void solve(int node, int sum, int nodes){ if (sum + node <= this.circles && sum + node + (this.count - nodes - 1)*10 >= 90 ){ if (nodes + 1 < this.count){ for (int i = 0; i < 11; i++){ solve(i, sum + node, nodes + 1); } }else{ if (sum + node == this.circles){ this.sum++; } } } } } }