特色:html
There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.java
Could you please decide the first player will win or lose?數組
Have you met this question in a real interview? Yes
Example
Given array A = [3,2,2], return true.ide
Given array A = [1,2,4], return true.wordpress
Given array A = [1,20,4], return false.優化
來來來, 先畫個圖:ui
如圖, 咱們發現, 一下相同的重複的[2], 能夠用記憶花搜索. 可是, 假設咱們用一個狀態dp[1], 咱們不知道剩的一個, 是2, 是3仍是4啊. 由於如今取一個硬幣,能夠從左邊取, 也能夠從右邊取, 是有方向性的, 因此不能用dp[i]表示.
如今咱們呢, 用一個區間的兩個下標表示this
public class Solution { /** * @param values: an array of integers * @return: a boolean which equals to true if the first player will win */ public boolean firstWillWin(int[] values) { // write your code here int n = values.length; int[] sum = new int[n + 1]; sum[0] = 0; for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + values[i - 1]; // s[i][j] = sum[j + 1] - sum[i]; int[][] dp = new int[n][n]; for (int i = 0; i < n; ++i) dp[i][i] = values[i]; for (int len = 2; len <= n; ++len) { for (int i = 0; i < n; ++i) { int j = i + len - 1; if (j >= n) continue; int s = sum[j + 1] - sum[i]; dp[i][j] = Math.max(s - dp[i + 1][j], s - dp[i][j - 1]); } } return dp[0][n - 1] > sum[n] / 2; } } // 方法一 import java.util.*; public class Solution { /** * @param values: an array of integers * @return: a boolean which equals to true if the first player will win */ public boolean firstWillWin(int[] values) { // write your code here int n = values.length; int [][]dp = new int[n + 1][n + 1]; boolean [][]flag =new boolean[n + 1][n + 1]; int sum = 0; for(int now : values) sum += now; return sum <