File tree Expand file tree Collapse file tree 1 file changed +44
-1
lines changed
Expand file tree Collapse file tree 1 file changed +44
-1
lines changed Original file line number Diff line number Diff line change 55// 拿到最后一颗石子的人获胜,根据n、m返回谁赢
66public class Code01_BashGame {
77
8- public static String bashGame (int n , int m ) {
8+ // 动态规划进行所有尝试
9+ // 为了验证
10+ public static int MAXN = 1001 ;
11+
12+ public static String [][] dp = new String [MAXN ][MAXN ];
13+
14+ public static String bashGame1 (int n , int m ) {
15+ if (n == 0 ) {
16+ return "后手" ;
17+ }
18+ if (dp [n ][m ] != null ) {
19+ return dp [n ][m ];
20+ }
21+ String ans = "后手" ;
22+ for (int pick = 1 ; pick <= m ; pick ++) {
23+ if (bashGame1 (n - pick , m ).equals ("后手" )) {
24+ // 后续过程的后手,就是此时的先手
25+ ans = "先手" ;
26+ break ;
27+ }
28+ }
29+ dp [n ][m ] = ans ;
30+ return ans ;
31+ }
32+
33+ // 正式方法
34+ public static String bashGame2 (int n , int m ) {
935 return n % (m + 1 ) != 0 ? "先手" : "后手" ;
1036 }
1137
38+ // 为了验证
39+ public static void main (String [] args ) {
40+ int V = 500 ; // 需要比MAXN小
41+ int testTimes = 5000 ;
42+ System .out .println ("测试开始" );
43+ for (int i = 0 ; i < testTimes ; i ++) {
44+ int n = (int ) (Math .random () * V );
45+ int m = (int ) (Math .random () * V ) + 1 ;
46+ String ans1 = bashGame1 (n , m );
47+ String ans2 = bashGame2 (n , m );
48+ if (!ans1 .equals (ans2 )) {
49+ System .out .println ("出错了!" );
50+ }
51+ }
52+ System .out .println ("测试结束" );
53+ }
54+
1255}
You can’t perform that action at this time.
0 commit comments