爬楼梯
解法一
dp
class Solution { public int climbStairs(int n) { int dp[] = new int[n+1]; if(n <= 2) return n; dp[1] = 1; dp[2] = 2; for(int i = 3;i <= n;i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp[n]; } }
空间优化了一下
class Solution { public int climbStairs(int n) { int dp[] = new int[4]; if(n <= 2) return n; dp[1] = 1; dp[2] = 2; for(int i = 3;i <= n;i++){ dp[3] = dp[1] + dp[2]; dp[1] = dp[2]; dp[2] = dp[3]; } return dp[3]; } }
买卖股票的最佳时机
class Solution { public int maxProfit(int[] prices) { int res = 0; int min = Integer.MAX_VALUE; for(int i = 0;i < prices.length;i++){ res = Math.max(res,prices[i]-min); min = Math.min(min,prices[i]); } return res; } }
正则表达式匹配
class Solution { public boolean isMatch(String s, String p) { int m = s.length(); int n = p.length(); boolean[][] f = new boolean[m + 1][n + 1]; f[0][0] = true; for (int i = 0; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (p.charAt(j - 1) == '*') { f[i][j] = f[i][j - 2]; if (matches(s, p, i, j - 1)) { f[i][j] = f[i][j] || f[i - 1][j]; } } else { if (matches(s, p, i, j)) { f[i][j] = f[i - 1][j - 1]; } } } } return f[m][n]; } public boolean matches(String s, String p, int i, int j) { if (i == 0) { return false; } if (p.charAt(j - 1) == '.') { return true; } return s.charAt(i - 1) == p.charAt(j - 1); } }