62. 不同路径
class Solution { public int uniquePaths(int m, int n) { int[][] dep = new int[m][n]; for (int i = 0;i < m;i++){ dep[i][0] = 1; } for (int j = 1;j < n;j++){ dep[0][j] = 1; } for (int i = 1;i < m;i++){ for (int j = 1;j < n;j++){ dep[i][j] = dep[i - 1][j] + dep[i][j - 1]; } } return dep[m-1][n-1]; } }
63. 不同路径 II
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; int n = obstacleGrid[0].length; if (obstacleGrid[0][0] == 1){ return 0; } obstacleGrid[0][0] = 1; for (int i = 1;i < m;i++){ obstacleGrid[i][0] = (obstacleGrid[i][0] == 0 && obstacleGrid[i - 1][0] == 1) ? 1 : 0; } for (int j = 1;j < n;j++){ obstacleGrid[0][j] = (obstacleGrid[0][j] == 0 && obstacleGrid[0][j - 1] == 1) ? 1 : 0; } for (int i = 1;i < m;i++){ for (int j = 1;j < n;j++){ if (obstacleGrid[i][j] == 0){ obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1]; }else{ obstacleGrid[i][j] = 0; } } } return obstacleGrid[m - 1][n - 1]; } }
64. 最小路径和
class Solution { public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[][] dp = new int[m][n]; dp[0][0] = grid[0][0]; for (int i = 1;i < m;i++){ dp[i][0] = dp[i-1][0] + grid[i][0]; } for (int j = 1;j < n;j++){ dp[0][j] = dp[0][j-1] + grid[0][j]; } for (int i = 1;i < m;i++){ for (int j = 1;j < n;j++){ dp[i][j] = Math.min(dp[i - 1][j],dp[i][j - 1]) + grid[i][j]; } } return dp[m-1][n-1]; } }
121. 买卖股票的最佳时机
class Solution { public int maxProfit(int[] prices) { if (prices.length <= 1){ return 0; } int res = 0; int num = prices[0]; for (int i = 1;i < prices.length;i++){ if (prices[i] < num){ num = prices[i]; }else { res = Math.max(res,prices[i] - num); } } return res; } }
122. 买卖股票的最佳时机 II
class Solution { public int maxProfit(int[] prices) { if (prices.length <= 1){ return 0; } int res = 0; for (int i = 1;i < prices.length;i++){ if (prices[i] > prices[i - 1]){ res += prices[i] - prices[i - 1]; } } return res; } }
53. 最大子序和
class Solution { public int maxSubArray(int[] nums) { int sum = 0; int ans = nums[0]; for (int num : nums){ if (sum > 0){ sum += num; }else{ sum = num; } ans = Math.max(ans, sum); } return ans; } }
322. 零钱兑换
class Solution { public int coinChange(int[] coins, int amount) { if (amount == 0){ return 0; } int[] dp = new int[amount + 1]; for (int coin : coins){ for (int i = coin;i <= amount;i++){ if (i == coin){ dp[i] = 1; }else if (dp[i] == 0 && dp[i - coin] != 0){ dp[i] = dp[i -coin] + 1; }else if (dp[i - coin] != 0){ dp[i] = Math.min (dp[i], dp[i -coin] + 1); } } } return dp[amount] == 0 ? -1 : dp[amount]; } }
518. 零钱兑换 II
class Solution { public int change(int amount, int[] coins) { int[] dp = new int[amount + 1]; dp[0] = 1; for (int coin : coins){ for (int i = coin;i <= amount;i++){ dp[i] += dp[i - coin]; } } return dp[amount]; } }
51. N皇后
174. 地下城游戏