最大正方形
class Solution { public int maximalSquare(char[][] matrix) { int m = matrix.length; int n = matrix[0].length; int res = 0; int dp [][] = new int[m+1][n+1]; for(int i = 0;i < m;i++){ for(int j = 0;j < n;j++){ if(matrix[i][j] == '1'){ dp[i+1][j+1] = Math.min(dp[i][j+1],Math.min(dp[i][j],dp[i+1][j]))+ 1; res = Math.max(res,dp[i+1][j+1]); } } } return res*res; } }
完全平方数
class Solution { public int numSquares(int n) { int[] f = new int[n + 1]; for (int i = 1; i <= n; i++) { int minn = Integer.MAX_VALUE; for (int j = 1; j * j <= i; j++) { minn = Math.min(minn, f[i - j * j]); } f[i] = minn + 1; } return f[n]; } }
目标和
class Solution { public int findTargetSumWays(int[] nums, int target) { int sum = 0; for (int num : nums) { sum += num; } int diff = sum - target; if (diff < 0 || diff % 2 != 0) { return 0; } int n = nums.length, neg = diff / 2; int[][] dp = new int[n + 1][neg + 1]; dp[0][0] = 1; for (int i = 1; i <= n; i++) { int num = nums[i - 1]; for (int j = 0; j <= neg; j++) { dp[i][j] = dp[i - 1][j]; if (j >= num) { dp[i][j] += dp[i - 1][j - num]; } } } return dp[n][neg]; } }