[关闭]
@Yano 2015-12-30T11:25:28.000000Z 字数 13462 阅读 16382

LeetCode之Dynamic Programming题目汇总

LeetCode

我的博客:http://blog.csdn.net/yano_nankai
LeetCode题解:https://github.com/LjyYano/LeetCode


LeetCode 题目汇总

LeetCode之Array题目汇总
LeetCode之Hash Table题目汇总
LeetCode之Linked List题目汇总
LeetCode之Math题目汇总
LeetCode之String题目汇总
LeetCode之Binary Search题目汇总
LeetCode之Divide and Conquer题目汇总
LeetCode之Dynamic Programming题目汇总
LeetCode之Backtracing题目汇总
LeetCode之Stack题目汇总
LeetCode之Sort题目汇总
LeetCode之Bit Manipulation题目汇总
LeetCode之Tree题目汇总
LeetCode之Depth-first Search题目汇总
LeetCode之Breadth-first Search题目汇总
LeetCode之Graph题目汇总
LeetCode之Trie题目汇总
LeetCode之Design题目汇总


文章目录:


Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.


输入用例

  1. 递减, [5,4,3,2,1]
  2. 递增, [1,2,3,4,5]
  3. 有增有减

定义int型变量lowest,存储从prices[0..i]的最小值

  1. public int maxProfit(int[] prices) {
  2. if (prices.length <= 1) {
  3. return 0;
  4. }
  5. int maxProfit = 0;
  6. int lowest = Integer.MAX_VALUE;
  7. for (int v : prices) {
  8. lowest = Math.min(v, lowest);
  9. maxProfit = Math.max(maxProfit, v - lowest);
  10. }
  11. return maxProfit;
  12. }

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?


斐波那契数列的典型应用。

注意

  1. 不要使用递归,否则遇到大数时,递归太深,容易溢出,同时效率低
  2. 最好的方法是定义三个变量(不用建立数组),循环
  1. public int climbStairs(int n) {
  2. if (n < 0) {
  3. return -1;
  4. } else if (n <= 2) {
  5. return n;
  6. }
  7. // 定义三个变量,空间复杂度是O(1)
  8. int step1 = 1;
  9. int step2 = 2;
  10. int step3 = 0;
  11. // 三个变量一直循环
  12. // climbStairs(n) = climbStairs(n - 1) + climbStairs(n - 2)
  13. for (int i = 3; i <= n; i++) {
  14. step3 = step1 + step2;
  15. step1 = step2;
  16. step2 = step3;
  17. }
  18. return step3;
  19. }

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 an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.


  1. public int numDecodings(String s) {
  2. if (s == null || s.length() == 0) {
  3. return 0;
  4. }
  5. int n = s.length();
  6. char[] c = s.toCharArray();
  7. // 对于台阶,需要前两步的值,所以数组最小是3
  8. int[] step = new int[Math.max(n + 1, 3)];
  9. step[0] = 1;
  10. step[1] = 0;
  11. // 第一个字符不是0,则第一步初始为1
  12. if (c[0] != '0') {
  13. step[1] = 1;
  14. }
  15. // step[i] = step[i - 1] + step[i - 2];
  16. // 只不过加step[i - 2]时,需要对c[i - 2]和c[i - 1]判断,组合是否<=26
  17. for (int i = 2; i <= n; i++) {
  18. step[i] = 0;
  19. if (c[i - 1] != '0') {
  20. step[i] += step[i - 1];
  21. }
  22. if (c[i - 2] != '0') {
  23. if ((c[i - 2] - '0') * 10 + (c[i - 1] - '0') <= 26) {
  24. step[i] += step[i - 2];
  25. }
  26. }
  27. }
  28. return step[n];
  29. }

House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.


本质:求数组不相邻元素最大和

动态规划(背包问题):设P[i]表示从0~i个房间抢劫的最大收益。

每次迭代只需要P的两个元素,并不需要设数组P。设两个变量为:

  1. take :nums[i] + P[i-2]
  2. nonTake:P[i-1]
  1. public int rob(int[] nums) {
  2. int take = 0;
  3. int nonTake = 0;
  4. int max = 0;
  5. for (int i = 0; i < nums.length; i++) {
  6. take = nums[i] + nonTake;
  7. nonTake = max;
  8. max = Math.max(take, nonTake);
  9. }
  10. return max;
  11. }
  12. public int rob2(int[] nums) {
  13. if (nums.length == 0) {
  14. return 0;
  15. }
  16. if (nums.length == 1) {
  17. return nums[0];
  18. }
  19. int[] P = new int[nums.length];
  20. P[0] = nums[0];
  21. P[1] = Math.max(nums[0], nums[1]);
  22. for (int i = 2; i < nums.length; i++) {
  23. P[i] = Math.max(nums[i] + P[i - 2], P[i - 1]);
  24. }
  25. return P[nums.length - 1];
  26. }

House Robber II

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


参考:LeetCode 198 House Robber

只是这次变成了一个环,那么只要把数组分成两个:不包括第一个元素、不包括最后一个元素,就可以把环拆掉。取House Robber的最大值。

  1. public int rob(int[] nums) {
  2. if (nums == null || nums.length == 0) {
  3. return 0;
  4. }
  5. if (nums.length == 1) {
  6. return nums[0];
  7. }
  8. if (nums.length == 2) {
  9. return Math.max(nums[0], nums[1]);
  10. }
  11. return Math.max(help(Arrays.copyOfRange(nums, 0, nums.length - 1)),
  12. help(Arrays.copyOfRange(nums, 1, nums.length)));
  13. }
  14. public int help(int[] nums) {
  15. if (nums.length == 0) {
  16. return 0;
  17. }
  18. if (nums.length == 1) {
  19. return nums[0];
  20. }
  21. int[] P = new int[nums.length];
  22. P[0] = nums[0];
  23. P[1] = Math.max(nums[0], nums[1]);
  24. for (int i = 2; i < nums.length; i++) {
  25. P[i] = Math.max(nums[i] + P[i - 2], P[i - 1]);
  26. }
  27. return P[nums.length - 1];
  28. }

Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 4.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


动态规划,设dp[x][y]是当前matrix[x][y]最大的正方形的长。

  1. public int maximalSquare(char[][] matrix) {
  2. if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  3. return 0;
  4. }
  5. int mx = matrix.length;
  6. int my = matrix[0].length;
  7. int[][] dp = new int[mx][my];
  8. int max = 0;
  9. // 初始化第0行
  10. for (int i = 0; i < my; i++) {
  11. if (matrix[0][i] == '1') {
  12. dp[0][i] = 1;
  13. max = 1;
  14. }
  15. }
  16. // 初始化第0列
  17. for (int i = 1; i < mx; i++) {
  18. if (matrix[i][0] == '1') {
  19. dp[i][0] = 1;
  20. max = 1;
  21. }
  22. }
  23. // dp[x][y] = min(dp[x-1][y], dp[x][y-1], dp[x-1][y-1]) + 1
  24. for (int x = 1; x < mx; x++) {
  25. for (int y = 1; y < my; y++) {
  26. if (matrix[x][y] == '1') {
  27. dp[x][y] = Math.min(Math.min(dp[x - 1][y], dp[x][y - 1]),
  28. dp[x - 1][y - 1]) + 1;
  29. max = Math.max(max, dp[x][y]);
  30. }
  31. }
  32. }
  33. return max * max;
  34. }

Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.


参考:LeetCode 053 Maximum Subarray

LeetCode第53题Maximum Subarray是求连续和最大的子数组,本题是求连续乘积最大的子数组。

在解法上是一样的,只是在求和时,是负就舍弃。但是在乘积中,因为负数*负数=正数,所以连续乘积为负数时,并不能舍弃这个数,因为如果数组的元素是负数,它可能成为乘积最大的数。

所以LeetCode第53题Maximum Subarray,只需要定义一个变量,用来记录和;本题要定义两个变量:positive和negative,分别记录当前乘积最大值和最小值。

  1. public int maxProduct(int[] nums) {
  2. int max = nums[0];
  3. int positive = nums[0];
  4. int negative = nums[0];
  5. for (int i = 1; i < nums.length; i++) {
  6. positive *= nums[i];
  7. negative *= nums[i];
  8. if (positive < negative) {
  9. int t = positive;
  10. positive = negative;
  11. negative = t;
  12. }
  13. positive = Math.max(positive, nums[i]);
  14. negative = Math.min(negative, nums[i]);
  15. max = Math.max(max, positive);
  16. }
  17. return max;
  18. }

Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


  1. public int maxSubArray(int[] nums) {
  2. if (nums == null || nums.length == 0) {
  3. return 0;
  4. }
  5. int curSum = nums[0];
  6. int maxSum = nums[0];
  7. for (int i = 1; i < nums.length; i++) {
  8. curSum = Math.max(curSum + nums[i], nums[i]);
  9. maxSum = Math.max(curSum, maxSum);
  10. }
  11. return maxSum;
  12. }

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.


LeetCode 063 Unique Paths II 
LeetCode 062 Unique Paths

  1. public int minPathSum(int[][] grid) {
  2. if (grid == null || grid[0] == null) {
  3. return 0;
  4. }
  5. int m = grid.length;
  6. int n = grid[0].length;
  7. int[][] dp = new int[m][n];
  8. dp[0][0] = grid[0][0];
  9. for (int y = 1; y < n; y++) {
  10. dp[0][y] = dp[0][y - 1] + grid[0][y];
  11. }
  12. for (int x = 1; x < m; x++) {
  13. dp[x][0] = dp[x - 1][0] + grid[x][0];
  14. }
  15. for (int y = 1; y < n; y++) {
  16. for (int x = 1; x < m; x++) {
  17. int min = Math.min(dp[x - 1][y], dp[x][y - 1]);
  18. dp[x][y] = min + grid[x][y];
  19. }
  20. }
  21. return dp[m - 1][n - 1];
  22. }

Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


动态规划,求解最优化问题,自底向上。

  1. public int numSquares(int n) {
  2. int[] dp = new int[n + 1];
  3. Arrays.fill(dp, Integer.MAX_VALUE);
  4. // 将所有平方数置1
  5. for (int i = 0; i * i <= n; i++) {
  6. dp[i * i] = 1;
  7. }
  8. for (int a = 1; a <= n; a++) {
  9. for (int b = 1; a + b * b <= n; b++) {
  10. // 取较小值,a + b * b也可能是平方数
  11. dp[a + b * b] = Math.min(dp[a] + 1, dp[a + b * b]);
  12. }
  13. }
  14. return dp[n];
  15. }

Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.


定义一个数组K,自下向上存储结果,当处理到第一行时,K[0]就是结果。

在本题中,数组K分别是:

  1. [7, 6, 10, 3]
  2. [9, 10, 10, 3]
  3. [11, 10, 10, 3]

存储结果的部分是:

  1. [7, 6, 10]
  2. [9, 10]
  3. [11]

分析数字7,是题目输入的第三行的6,与其下面相邻的4和1的组合,取最小值; 
分析数字9,是题目输入的第二行的3,与数组[7, 6, 10]中的7和6的组合,取最小值。

核心代码是:

  1. for (int i = s.length - 2; i >= 0; i--) {
  2. List<Integer> list = triangle.get(i);
  3. for (int j = 0; j <= i; j++) {
  4. s[j] = list.get(j) + Math.min(s[j], s[j + 1]);
  5. }
  6. }
  1. public int minimumTotal(List<List<Integer>> triangle) {
  2. int size = triangle.size();
  3. if (size == 0) {
  4. return 0;
  5. }
  6. if (size == 1) {
  7. return triangle.get(0).get(0);
  8. }
  9. int[] s = new int[size];
  10. int k = 0;
  11. for (Integer v : triangle.get(size - 1)) {
  12. s[k++] = v;
  13. }
  14. for (int i = s.length - 2; i >= 0; i--) {
  15. List<Integer> list = triangle.get(i);
  16. for (int j = 0; j <= i; j++) {
  17. s[j] = list.get(j) + Math.min(s[j], s[j + 1]);
  18. }
  19. }
  20. return s[0];
  21. }

Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

Hint:

  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


  1. public int nthUglyNumber(int n) {
  2. int[] nums = new int[n];
  3. nums[0] = 1;
  4. int i = 0, j = 0, k = 0, t = 1;
  5. while (t < n) {
  6. int min = Math.min(Math.min(nums[i] * 2, nums[j] * 3), nums[k] * 5);
  7. nums[t++] = min;
  8. if (nums[i] * 2 == min) {
  9. i++;
  10. }
  11. if (nums[j] * 3 == min) {
  12. j++;
  13. }
  14. if (nums[k] * 5 == min) {
  15. k++;
  16. }
  17. }
  18. return nums[n - 1];
  19. }

Unique Binary Search Trees

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

For example,
Given n = 3, there are a total of 5 unique BST's.

  1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

  1. 以n为根结点的二叉树个数=左子树个数*右子树个数
  2. 用数组record[n+1]记录以0~n的情况,自底向上,否则会超时
  1. public int numTrees(int n) {
  2. if (n == 1 || n == 2) {
  3. return n;
  4. }
  5. // record[0]没有用,所以长度是n+1
  6. // 使用数组,从下向上保存结果,能够节省时间,否则会超时
  7. int[] record = new int[n + 1];
  8. record[0] = 1;
  9. record[1] = 1; // 1个元素时,情况为1
  10. record[2] = 2; // 2个元素时,情况为2
  11. for (int i = 3; i <= n; i++) {
  12. int tmp = 0;
  13. for (int k = 0; k < i; k++) {
  14. // 以n为根结点的二叉树个数=左结点的二叉树个数*右结点的二叉树个数
  15. // 题目所求要包括所有情况,分别以1~n为根结点
  16. tmp += (record[k] * record[i - k - 1]);
  17. }
  18. // 记录1~i时,BST的个数
  19. record[i] = tmp;
  20. }
  21. return record[n];
  22. }

Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


  1. public List<TreeNode> generateTrees(int n) {
  2. int[] array = new int[n];
  3. // 建立1~n的数组
  4. for (int i = 0; i < n; i++) {
  5. array[i] = i + 1;
  6. }
  7. return generateTrees(array);
  8. }
  9. List<TreeNode> generateTrees(int[] array) {
  10. if (array.length == 0) {
  11. return new ArrayList<TreeNode>(
  12. Collections.<TreeNode> singletonList(null));
  13. }
  14. ArrayList<TreeNode> rt = new ArrayList<TreeNode>();
  15. // 数组的每一个元素(array[i]),分别作为根结点
  16. for (int i = 0; i < array.length; i++) {
  17. // array[i]作为根结点,array[i]之前的元素为左结点,array[i]之后的元素为右结点
  18. for (TreeNode left : generateTrees(Arrays.copyOfRange(array, 0, i))) {
  19. for (TreeNode right : generateTrees(Arrays.copyOfRange(array,
  20. i + 1, array.length))) {
  21. TreeNode root = new TreeNode(array[i]);
  22. root.left = left;
  23. root.right = right;
  24. rt.add(root);
  25. }
  26. }
  27. }
  28. return rt;
  29. }

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?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.


构造二维数组dp[m][n],其中

其中dp[m-1][n-1]就是结果。

  1. public int uniquePaths(int m, int n) {
  2. if (m <= 0 || n <= 0) {
  3. return 0;
  4. }
  5. int[][] dp = new int[m][n];
  6. for (int y = 1; y < n; y++) {
  7. dp[0][y] = 1;
  8. }
  9. for (int x = 1; x < m; x++) {
  10. dp[x][0] = 1;
  11. }
  12. for (int y = 1; y < n; y++) {
  13. for (int x = 1; x < m; x++) {
  14. dp[x][y] = dp[x - 1][y] + dp[x][y - 1];
  15. }
  16. }
  17. return dp[m - 1][n - 1];
  18. }

Unique Paths II

Follow up for "Unique Paths":

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.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.


参考LeetCode 062 Unique Paths

有障碍物的时候(obstacleGrid[i][j]==1),将对应的dp置0(dp[i][j]=0)。

  1. public int uniquePathsWithObstacles(int[][] obstacleGrid) {
  2. if (obstacleGrid == null || obstacleGrid[0] == null) {
  3. return 0;
  4. }
  5. if (obstacleGrid[0][0] == 1) {
  6. return 0;
  7. }
  8. int m = obstacleGrid.length;
  9. int n = obstacleGrid[0].length;
  10. int[][] dp = new int[m][n];
  11. for (int y = 1; y < n; y++) {
  12. if (obstacleGrid[0][y] == 0) {
  13. dp[0][y] = 1;
  14. } else {
  15. break;
  16. }
  17. }
  18. for (int x = 1; x < m; x++) {
  19. if (obstacleGrid[x][0] == 0) {
  20. dp[x][0] = 1;
  21. } else {
  22. break;
  23. }
  24. }
  25. for (int y = 1; y < n; y++) {
  26. for (int x = 1; x < m; x++) {
  27. if (obstacleGrid[x][y] == 1) {
  28. dp[x][y] = 0;
  29. } else {
  30. dp[x][y] = dp[x - 1][y] + dp[x][y - 1];
  31. }
  32. }
  33. }
  34. return dp[m - 1][n - 1];
  35. }

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注