Leetcode DP 动态规划问题

5. Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.

思路:

  • 初始条件 d[i][i] = true;
    if s[i] ==s[i-1], d[i][i+1] = ture;
  • 状态方程d[i][j] = d[i+1][j-1]&&(s[i+1]==s[j-1]);
class Solution {
    public String longestPalindrome(String s) 
    {   
         if(s == null || s.length() == 0) {
            return "";
        }
        
        int n = s.length(); int[] index = new int[2]; int max = 0;
        boolean[][] d = new boolean [n][n];
        
        
        //初始条件 d[i][i] = true;
        // if s[i] ==s[i-1], d[i][i+1] = ture;
        for(int i=0; i<n; i++) d[i][i] = true;
        for(int i=0; i<n-1; i++){
            if(s.charAt(i)==s.charAt(i+1))
                d[i][i+1] =true;
        }
        
        //状态方程d[i][j] = d[i+1][j-1]&&(s[i+1]==s[j-1]);
        for(int i= n-1;  i>=0 ; i--)
        {
            for(int j = i; j<n; j++ )
            {   
         
                if( j-i>=2 && d[i+1][j-1] && s.charAt(i)==s.charAt(j))
                    d[i][j] = true;
                
                if(j-i+1>max &&d[i][j] )
                {   
                    max = j-i+1;
                    index[0] = i ;
                    index[1] = j;
                } 
            }
        }
        
       
        return s.substring(index[0],index[1]+1);
        
    }
}


53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

思路:

  • 找到 以nums[i]结尾的子数组 ,找出他们最大sum d[i],
  • 状态方程d[i+1] = max(d[i]+nums[i],nums[i])
class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int [] d = new  int[n];
        d[0] = nums[0];
        int max = d[0];
        
        if(n==1) return nums[0];
        
        // 找到 以nums[i]结尾的子数组 ,找出他们最大sum d[i]
        // 状态方程d[i+1] = max(d[i]+nums[i],nums[i])
        for(int i =1 ; i<n; i++)
        {
            d[i] = Math.max(d[i-1]+nums[i],nums[i]);
            max = Math.max(max, d[i]);
        }
     
        return max;
    }
}

62. Unique Paths

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

How many possible unique paths are there?

思路:

  • 初始状态:f(0,j) = 1; f(i,0) = 1;
  • 状态方程: f(m,n) = f(m-1,n)+f(m,n-1)
class Solution {
    public int uniquePaths(int m, int n) {
        
        int[][] d = new int [m][n];
        
        // 初始状态:f(0,j) = 1; f(i,0) = 1;
        for(int i = 0; i<m; i++) d[i][0] = 1;
        for(int j = 0; j<n; j++) d[0][j] = 1;
        
        // 状态方程: f(m,n) = f(m-1,n)+f(m,n-1)
        for(int i = 1; i<m; i++)
        {
            for(int j = 1; j<n; j++)
            {
                d[i][j] = d[i-1][j] +d[i][j-1];
            }
        }
       
        return d[m-1][n-1];
    }
}

63. Unique Paths II

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:

  1. Right -> Right -> Down -> Down
  2. Down -> Down -> Right -> Right

思路:

  • 将obstacle的值 从(0,1)转换成(1,0)
  • 初始状态:f(0,j) = obstacle[0][j]*f(0,j-1); f(i,0) = obstacle[i][0]*f(i-1,0);
  • 状态方程: f(m,n) = obstacle[m-1][n]*f(m-1,n)+obstacle[m][n-1]*f(m,n-1)
class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        // empty
        if(obstacleGrid.length == 0) return 0;
        
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] d = new int[m][n];
        
        // 将(0,1)换成(1,0)
        for(int i=0; i<m;i++){
            for(int j=0; j<n;j++){
                obstacleGrid[i][j]=-obstacleGrid[i][j]+1;
            }
        }
        
        d[0][0] =  obstacleGrid[0][0];
            
        // 初始条件  f(0,j)=obstableGreid[0][j]*d[0][j-1]; 
        //          f(i,0)=obstableGreid[i][0]*d[i-1][0];
        for(int i=1; i<m;i++) d[i][0] = obstacleGrid[i][0]*d[i-1][0];
        for(int j=1; j<n;j++) d[0][j] = obstacleGrid[0][j]*d[0][j-1];
        
        //状态方程f(x,y)=obstableGreid[x-1][y]*f(x-1,y)+obstableGreid[x][y-1]*f(x,y-1)
        for(int i=1; i<m;i++){
            for(int j=1; j<n; j++){
                d[i][j] = obstacleGrid[i-1][j]*d[i-1][j]+obstacleGrid[i][j-1]*d[i][j-1];
            }
        }
        return d[m-1][n-1]*obstacleGrid[m-1][n-1];
    }
}

64. Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example:

Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

思路:

  • 初始状态:if d==null || d.length ==0;, return 0; d[0][0] = grid[0][0];
    d[0][j] = d[0][j-1]+grid[0][j-1]; d[i][0] = d[i-1][0]+grid[i-1][0];
  • 状态方程:d[i][j] = min(d[i-1][j]+grid[i-1][j],d[i][j-1]+grid[i][j-1]);
  • 最后输出的sum = d[m-1][n-1]+grid[m-1][n-1];
class Solution {
    public int minPathSum(int[][] grid) {

        if (grid==null || grid.length ==0) return 0;
        int m = grid.length; 
        int n = grid[0].length;
        int d[][] = new int[m][n];
        d[0][0] = 0;
        
        // 初始状态:if d==null || d.length ==0;, return 0; d[0][0] = 0; 
        //  d[0][j] = d[0][j-1]+grid[0][j-1]; d[i][0] = d[i-1][0]+grid[i-1][0];
        for(int i= 1;i<m ;i++)  d[i][0]  = d[i-1][0]+grid[i-1][0];
        for(int j= 1; j<n; j++) d[0][j]  = d[0][j-1]+grid[0][j-1]; 
        
        // 状态方程:d[i][j] = min(d[i-1][j]+grid[i-1][j],d[i][j-1]+grid[i][j-1]);
         for(int i= 1;i<m ;i++)
         {
              for(int j= 1; j<n; j++)
              {
                  d[i][j] = Math.min(d[i-1][j]+grid[i-1][j],d[i][j-1]+grid[i][j-1]);
                  
              }
         }
        return d[m-1][n-1]+grid[m-1][n-1];
    }
}


70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps

思路:

  • 初始状态:d[1] = 1 ; d[2] = 2;
  • 状态方程:d[n] = d[n-1]+ d[n-2] (n>=3)
class Solution {
    public int climbStairs(int n) {
        int [] d = new int[n];
        
        //初始状态:d[1] = 1 ; d[2] = 2;
        //状态方程:d[n] = d[n-1]+[n-2](n>=3)
        for(int i=0; i<n; i++)
        {   
            if(i<2) d[i] = i+1;
            
            else d[i] = d[i-1]+d[i-2];
        }
        return d[n-1];
    }
}

91. Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

‘A’ -> 1
‘B’ -> 2

‘Z’ -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: “12”
Output: 2
Explanation: It could be decoded as “AB” (1 2) or “L” (12).

思路:

  • 初始状态:
  • 状态方程:d[n] = d[n-1]+ d[n-2]
class Solution {
    public int numDecodings(String s) {
        //empty
        if(s==null && s.length()==0) return 0;
        
        //初始化
        int n =s.length();
        int[] d = new int[n];
        d[0]= s.charAt(0) =='0'?0:1;
        
        for(int i=1; i<n; i++){
            int forward_one = Integer.valueOf(s.substring(i,i+1));
            int forward_two = Integer.valueOf(s.substring(i-1,i+1));
            
            if(forward_one !=0){
                d[i] = d[i-1];
            }
            
            if(forward_two>=10&&forward_two<=26){
                d[i] += i>=2 ?d[i-2]:1;
            }
        }
        return d[n-1];
    }
}

96. Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST’s:

思路:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> ans = new ArrayList<TreeNode> ();
        
        if(n==0) return ans;
        return getAns(1,n);
        
    }
    private List<TreeNode>  getAns(int start, int end){
        List<TreeNode> ans = new ArrayList<TreeNode> ();
        
        if(start>end){
            ans.add (null); 
            return ans;
        }
        
        if(start ==end ){
            TreeNode tree = new TreeNode(start);
            ans.add(tree);
            return ans;
        }
        
        for(int i =start ; i<=end;i++){
            List<TreeNode> leftTrees = getAns (start ,i-1);
            List<TreeNode> rightTrees = getAns (i+1 ,end);
            
            for(TreeNode leftTree :leftTrees){
                for(TreeNode rightTree: rightTrees){
                    TreeNode root= new TreeNode(i);
                    root.left = leftTree;
                    root.right = rightTree;
                    ans.add(root);
                }
            }
        }
            return ans;
    }
}

95. Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.

Example:

Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]

class Solution {
    public int numTrees(int n) {
        int [] d = new int [n+1];
        d[0] =d[1] = 1;
        for(int i=2; i<=n;i++){
            for(int j=0;j<i;j++){
                d[i] +=  d[j]*d[i-j-1];
            }
        }
        return d[n];
    }
}
发布了12 篇原创文章 · 获赞 0 · 访问量 896

猜你喜欢

转载自blog.csdn.net/EPFL_Panda/article/details/100763908
今日推荐