动态规划
1. 最大连续子序列和
https://leetcode.com/problems/maximum-subarray/discuss/
1 public class Solution { 2 public int FindGreatestSumOfSubArray(int[] array) { 3 int n = array.length; 4 int[] dp = new int[n]; 5 dp[0] = array[0]; 6 int res = dp[0]; 7 8 for (int i = 1; i < n; i++) { 9 dp[i] = array[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); 10 res = Math.max(res, dp[i]); 11 } 12 return res; 13 } 14 }
2. 最长递增子序列
https://leetcode.com/problems/longest-increasing-subsequence/solution/
1 public class Solution { 2 public int lengthOfLIS(int[] nums) { 3 int[] dp = new int[nums.length]; 4 int len = 0; 5 for (int num : nums) { 6 int i = Arrays.binarySearch(dp, 0, len, num); 7 if (i < 0) { 8 i = -(i + 1); 9 } 10 dp[i] = num; 11 if (i == len) { 12 len++; 13 } 14 } 15 return len; 16 } 17 }
扩展:找出最长递增子序列
3. 最长回文子串
1 class Solution { 2 private int max = 0; 3 private String res = ""; 4 5 public String longestPalindrome(String s) { 6 if (s.length() == 1) 7 return s; 8 for (int i = 0; i < s.length() - 1; i++) { 9 checkPalindromeExpand(s, i, i); 10 checkPalindromeExpand(s, i, i + 1); 11 } 12 return res; 13 } 14 15 private void checkPalindromeExpand(String s, int low, int high) { 16 while (low >= 0 && high < s.length()) { 17 if (s.charAt(low) == s.charAt(high)) { 18 if (high - low + 1 > max) { 19 max = high - low + 1; 20 res = s.substring(low, high + 1); 21 } 22 low--; 23 high++; 24 } else { 25 return; 26 } 27 } 28 } 29 }
4. 最长回文子序列
5. 最长公共子串
6. 最长公共子序列
7. 矩阵的最小路径和
1 package coding; 2 3 /** 4 * Created by sakura on 2018/3/18. 5 */ 6 public class Solution187 { 7 public static void main(String[] args) { 8 int[][] array={{1,3,5,9},{8,1,3,4},{5,0,6,1},{8,8,4,0}}; 9 System.out.println(minPathSum1(array)); 10 System.out.println(minPathSum2(array)); 11 } 12 13 //时间复杂度O(M*N),空间复杂度O(M*N) 14 public static int minPathSum1(int[][] m){ 15 if(m==null||m.length==0||m[0]==null||m[0].length==0){ 16 return 0; 17 } 18 int row=m.length; 19 int col=m[0].length; 20 int[][] dp=new int[row][col]; 21 dp[0][0]=m[0][0]; 22 23 for(int i=1;i<row;i++){ 24 dp[i][0]=dp[i-1][0]+m[i][0]; 25 } 26 for(int j=1;j<col;j++){ 27 dp[0][j]=dp[0][j-1]+m[0][j]; 28 } 29 for(int i=1;i<row;i++){ 30 for(int j=1;j<col;j++){ 31 dp[i][j]=Math.min(dp[i-1][j],dp[i][j-1])+m[i][j]; 32 } 33 } 34 return dp[row-1][col-1]; 35 } 36 37 //空间压缩,时间复杂度O(M*N),空间复杂度O(min{M,N}) 38 public static int minPathSum2(int[][] m){ 39 if(m==null||m.length==0||m[0]==null||m[0].length==0){ 40 return 0; 41 } 42 int more=Math.max(m.length,m[0].length); 43 int less=Math.min(m.length,m[0].length); 44 boolean rowmore=more==m.length; 45 int[] arr=new int[less]; 46 arr[0]=m[0][0]; 47 48 for(int i=1;i<less;i++){ 49 arr[i]=arr[i-1]+(rowmore?m[0][i]:m[i][0]); 50 } 51 for(int i=1;i<more;i++){ 52 arr[0]=arr[0]+(rowmore?m[i][0]:m[0][i]); 53 for(int j=1;j<less;j++){ 54 arr[j]=Math.min(arr[j-1],arr[j]) 55 +(rowmore?m[i][j]:m[j][i]); 56 } 57 } 58 return arr[less-1]; 59 } 60 }