classSolution { public: intmaxSubArray(vector<int>& nums){ int cur = 0, ans = nums[0]; for(int i = 0; i < nums.size(); ++i){ cur += nums[i]; if(cur > ans) ans = cur; if(cur < 0) cur = 0; } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defmaxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ ans, cur = nums[0], 0 for x in nums: cur += x if cur > ans: ans = cur if cur < 0: cur = 0 return ans
classSolution { intdivide_and_conquer(int l, int r, const vector<int> &nums){ if (l == r) return nums[l]; int mid = (l + r) >> 1; int left = INT_MIN, right = left; int cur = 0; for (int i = mid; i >= l; --i) { cur += nums[i]; if (cur > left) left = cur; } cur = 0; for (int i = mid + 1; i <= r; ++i) { cur += nums[i]; if (cur > right) right = cur; } returnmax(left + right, max(divide_and_conquer(l,mid,nums), divide_and_conquer(mid + 1, r, nums))); }
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?
It's true that this can be solved with dynamic programming. But you can see that every path has exactly m - 1 horizontal moves and n - 1 vertical moves. So, to get a particular path, you need to choose where to put your m - 1 horizontal moves (or your n - 1 vertical moves) amongst the m + n - 2 total moves. That gives (m+n-2 choose m-1) paths (or (m+n-2 choose n-1), which is the same).
C++
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intuniquePaths(int m, int n){ vector<vector<int>> dp(m, vector<int>(n, 0)); for(int i = 0; i < n; ++i) dp[0][i] = 1; for(int i = 0; i < m; ++i) dp[i][0] = 1; for(int i = 1; i < m; ++i) for(int j = 1; j < n; ++j) dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; return dp[m - 1][n - 1]; } };
Python方法1
1 2 3 4 5 6 7 8 9 10
class Solution: # @return an integer def uniquePaths(self, m, n): dp =[[0 for i in range(n+1)] for i in range(m+1)] for i in range(1,n+1): dp[1][i] = 1 for i in range(2,m+1): for j in range(1,n+1): dp[i][j]=dp[i-1][j]+dp[i][j-1] return dp[m][n]
Python 方法2
1 2 3 4
class Solution: # @return an integer def uniquePaths(self, m, n): return math.factorial(m+n-2)/(math.factorial(n-1)*math.factorial(m-1))
63. 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.
classSolution { public: intuniquePathsWithObstacles(vector<vector<int>>& obstacleGrid){ if(obstacleGrid.empty() obstacleGrid[0].empty()) return0; int m = obstacleGrid.size(), n = obstacleGrid[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); dp[0][0] = obstacleGrid[0][0] ^ 1; for(int i = 1; i < n; ++i) dp[0][i] = dp[0][i - 1] & (!obstacleGrid[0][i]); for(int i = 1; i < m; ++i) dp[i][0] = dp[i - 1][0] & (!obstacleGrid[i][0]); for(int i = 1; i < m; ++i) for(int j = 1; j < n; ++j) dp[i][j] = obstacleGrid[i][j]? 0 : dp[i - 1][j] + dp[i][j - 1]; return dp[m - 1][n - 1]; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: # @param obstacleGrid, a list of lists of integers # @return an integer defuniquePathsWithObstacles(self, obstacleGrid): m , n = len(obstacleGrid) , len(obstacleGrid[0]) dp = [[0for x inrange(n+1)] for x inrange(m+1)] for j inrange(1,n+1): if obstacleGrid[0][j-1]: break else: dp[1][j] = 1 for i inrange(2,m+1): for j inrange(1,n+1): if obstacleGrid[i-1][j-1]: dp[i][j] = 0 else: dp[i][j]=dp[i-1][j]+dp[i][j-1] return dp[m][n]
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.
classSolution { public: intminPathSum(vector<vector<int>>& grid){ if(grid.empty() grid[0].empty()) return0; int m = grid.size(), n = grid[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); dp[0][0] = grid[0][0]; for(int i = 1; i < n; ++i) dp[0][i] = dp[0][i - 1] + grid[0][i]; for(int i = 1; i < m; ++i) dp[i][0] = dp[i - 1][0] + grid[i][0]; for(int i = 1; i < m; ++i) for(int j = 1; j < n; ++j) dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; return dp[m - 1][n - 1]; } };
版本2
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intminPathSum(vector<vector<int>> &grid){ int m = grid.size(), n = grid[0].size(); vector<vector<int>> dp(m+1, vector<int>(n+1, 0x7ffffff)); dp[0][1] = dp[1][0] = 0; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1]; return dp[m][n]; } };
Python
1 2 3 4 5 6 7 8 9 10 11
classSolution: # @param grid, a list of lists of integers # @return an integer defminPathSum(self, grid): m , n = len(grid) , len(grid[0]) dp = [[0x7ffffffffor x inrange(n+1)] for x inrange(m+1)] dp[0][1] = dp[1][0] = 0 for i inrange(1,m+1): for j inrange(1,n+1): dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1] return dp[m][n]
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.
classSolution { public: intclimbStairs(int n){ int zero = 0, one = 1, two=1; for (int i = 1; i <= n; i++){ two = zero + one; zero = one; one = two; } return two; } };
Python
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): defclimbStairs(self, n): """ :type n: int :rtype: int """ zero, one, two = 0, 1, 1 for i inrange(1, n + 1): two = zero + one zero, one = one, two return two
classSolution(object): defjudge(self, s1, s2, dp): if (s1, s2) in dp: return dp[s1, s2] if s1 == s2: dp[s1, s2] = True returnTrue ifsorted(s1) != sorted(s2): returnFalse
for i inrange(1, len(s1)): if self.judge(s1[:i], s2[:i], dp) and self.judge(s1[i:], s2[i:], dp) or \ self.judge(s1[:i], s2[-i:], dp) and self.judge(s1[i:], s2[:-i], dp): dp[s1, s2] = True returnTrue
classSolution(object): defisInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ m, n = len(s1), len(s2) iflen(s3) != m + n: returnFalse dp = [[False] * (n + 1) for _ inrange(m + 1)] dp[0][0] = True for i inrange(1, m + 1): dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1] for j inrange(1, n + 1): dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]
for i inrange(1, m + 1): for j inrange(1, n + 1): dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) \ or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]) return dp[m][n]
115. Distinct Subsequences
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
classSolution { public: intnumDistinct(string s, string t){ int m = s.size(), n = t.size(); if(n > m) return0; vector<vector<int>> dp(m, vector<int>(n, 0)); for(int i = 0; i < m; ++i) dp[i][0] = (s[i] == t[0]) + (i > 0? dp[i - 1][0] : 0); for(int i = 1; i < m; ++i){ for(int j = 1; j < n; ++j){ if(s[i] == t[j]) dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; else dp[i][j] = dp[i - 1][j]; } } return dp[m - 1][n - 1]; } };
另一种写法:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intnumDistinct(string s, string t){ int m = s.size(), n = t.size(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (int i = 0; i <= m; i++) dp[i][0] = 1; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s[i - 1] == t[j - 1]) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1]; else dp[i][j] = dp[i - 1][j]; } } return dp[m][n];
} };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: # @return an integer defnumDistinct(self, S, T): m , n = len(S),len(T) dp =[[0for j inrange(n+1)]for i inrange(m+1)] for i in xrange(0,m+1): dp[i][0]=1 for i in xrange(1,m+1): for j in xrange(1,n+1): if S[i-1]==T[j-1]: dp[i][j]=dp[i-1][j-1]+dp[i-1][j] else: dp[i][j]=dp[i-1][j]
return dp[m][n]
120. 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
1 2 3 4 5 6
[ [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.
classSolution(object): defwordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ n , dp = len(s),[True] + [False]*len(s) for i in xrange(n): for j in xrange(i+1): if dp[j] and s[j:i+1] in wordDict: dp[i+1]=True break return dp[n]
140. Word Break II
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given s = "catsanddog", dict = ["cat", "cats", "and", "sand", "dog"].
classSolution(object): defwordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: List[str] """ ans = [] if self.check(s, wordDict): self.dfs(0, len(s), '', s, ans, wordDict) return ans
defcheck(self, s, wordDict): dp = [True] + [False] * len(s) n = len(s) for i in xrange(n): for j in xrange(i + 1): if dp[j] and s[j:i + 1] in wordDict: dp[i + 1] = True break return dp[n]
defdfs(self, cur, n, path, s, ans, wordDict): if cur == n: ans.append(path) return
for i in xrange(cur, n): if s[cur:i + 1] in wordDict and self.check(s[i + 1:n], wordDict): if path: self.dfs(i + 1, n, path + ' ' + s[cur:i + 1], s, ans, wordDict) else: self.dfs(i + 1, n, s[cur:i + 1], s, ans, wordDict)
152. 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.
classSolution: # @param A, a list of integers # @return an integer defmaxProduct(self, A): maxMul = minMul = ans = A[0] for i inrange(1, len(A)): t = maxMul maxMul = max(t * A[i], minMul * A[i], A[i]) minMul = min(t * A[i], minMul * A[i], A[i]) ans = max(maxMul, ans) return ans
174. Dungeon Game
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2 (K)
-3
-3
5
-10
1
-10
30
-5 (P)
Notes:
The knight's health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
classSolution { public: intcalculateMinimumHP(vector<vector<int>>& dungeon){ if (dungeon.empty()) return0; int m = dungeon.size(), n = dungeon[0].size(); vector<vector<longlong>> dp(m + 1, vector<longlong>(n + 1, INT_MAX)); dp[m - 1][n] = dp[m][n - 1] = 1; for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]; if(dp[i][j] <= 0) dp[i][j] = 1; } } return dp[0][0]; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defcalculateMinimumHP(self, dungeon): """ :type dungeon: List[List[int]] :rtype: int """ ifnot dungeon: return0 m, n = len(dungeon), len(dungeon[0]) dp = [[0x7ffffff] * (n + 1) for _ inrange(m + 1)] dp[m - 1][n] = dp[m][n - 1] = 1 for i inrange(m - 1, -1, -1): for j inrange(n - 1, -1, -1): dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]) return dp[0][0]
198. 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.
classSolution: # @param num, a list of integer # @return an integer defrob(self, num): ifnot num: return0 n = len(num) if n==1: return num[0] dp = [0]*n dp[0],dp[1] = num[0],max(num[1],num[0]) for i in xrange(2,n): dp[i]=max(dp[i-1],dp[i-2]+num[i]) return dp[n-1]
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.
if matrix[i][j]=='1' dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1
else dp[i][j] = 0
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: # @param {character[][]} matrix # @return {integer} defmaximalSquare(self, matrix): ifnot matrix: return0 m , n = len(matrix),len(matrix[0]) dp = [[0if matrix[i][j]=='0'else1for j in xrange(n)]for i in xrange(m)] for i in xrange(1,m): for j in xrange(1,n): if matrix[i][j] =='1': dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1 else: dp[i][j] = 0 ans = max([max(i) for i in dp]) return ans ** 2
712. Minimum ASCII Delete Sum for Two Strings
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
1 2 3 4 5 6
**Input:** s1 = "sea", s2 = "eat" **Output:** 231 **Explanation:** Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. Deleting "t" from "eat" adds 116 to the sum. At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
1 2 3 4 5 6 7
**Input:** s1 = "delete", s2 = "leet" **Output:** 403 **Explanation:** Deleting "dee" from "delete" to turn the string into "let", adds 100[d]+101[e]+101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum. At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
Note:
0 < s1.length, s2.length <= 1000.
All elements of each string will have an ASCII value in [97, 122].
classSolution { public: intminimumDeleteSum(string s1, string s2){ int two_string_sum = 0; for (int i = 0; i < s1.length(); i++) two_string_sum += s1[i]; for (int i = 0; i < s2.length(); i++) two_string_sum += s2[i];
classSolution(object): defminimumDeleteSum(self, s1, s2): """ :type s1: str :type s2: str :rtype: int """ two_sum = sum(ord(c) for c in s1) + sum(ord(c) for c in s2) ifnot s1 ornot s2: return two_sum
dp = [[0] * len(s2) for _ inrange(len(s1))] dp[0][0] = ord(s1[0]) if s1[0] == s2[0] else0
for i inrange(1, len(s1)): dp[i][0] = max(dp[i - 1][0], ord(s1[i])) if s1[i] == s2[0] else dp[i - 1][0] for j inrange(1, len(s2)): dp[0][j] = max(dp[0][j - 1], ord(s2[j])) if s1[0] == s2[j] else dp[0][j - 1]
for i inrange(1, len(s1)): for j inrange(1, len(s2)): if s1[i] == s2[j]: dp[i][j] = dp[i - 1][j - 1] + ord(s1[i]) else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return two_sum - (dp[-1][-1] << 1)
718. Maximum Length of Repeated Subarray
Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.
Example 1:
1 2 3 4 5 6 7
**Input:** A: [1,2,3,2,1] B: [3,2,1,4,7] **Output:** 3 **Explanation:** The repeated subarray with maximum length is [3, 2, 1].
classSolution { publicintfindLength(int[] A, int[] B) { if (A.length == 0 B.length == 0) return0; int[][] dp = newint[A.length + 1][B.length + 1]; intans=0; for (inti=1; i <= A.length; i++) { for (intj=1; j <= B.length; j++) { dp[i][j] = A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1 : 0; ans = Math.max(ans, dp[i][j]); } } return ans; } }
还可以用滚动数组优化空间复杂度O(n)
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publicintfindLength(int[] A, int[] B) { if (A.length == 0 B.length == 0) return0; int[] dp = newint[B.length + 1]; intans=0; for (inti=1; i <= A.length; i++) { for (intj= B.length; j >= 1; j--) { dp[j] = A[i - 1] == B[j - 1] ? dp[j - 1] + 1 : 0; ans = Math.max(ans, dp[j]); } } return ans; } }
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): deffindLength(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: int """ dp = [0] * (len(B) + 1) ans = 0 for i inrange(1, len(A) + 1): for j inrange(len(B), 0, -1): dp[j] = (dp[j - 1] + 1) if A[i - 1] == B[j - 1] else0 ans = max(ans, dp[j]) return ans
799. Champagne Tower
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup (250ml) of champagne.
Then, some champagne is poured in the first glass at the top. When the top most glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has it's excess champagne fall on the floor.)
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
Now after pouring some non-negative integer cups of champagne, return how full the j-th glass in the i-th row is (both i and j are 0 indexed.)
Example 1: Input: poured = 1, query_glass = 1, query_row = 1 Output: 0.0 Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
Example 2: Input: poured = 2, query_glass = 1, query_row = 1 Output: 0.5 Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
Note:
poured will be in the range of [0, 10 ^ 9]. query_glass and query_row will be in the range of [0, 99].
classSolution(object): defchampagneTower(self, poured, query_row, query_glass): """ :type poured: int :type query_row: int :type query_glass: int :rtype: float """ dp = [[0] * (i + 1) for i inrange(query_row + 1)] dp[0][0] = poured for i inrange(query_row): for j inrange(i + 1): cur = (dp[i][j] - 1) / 2.0if dp[i][j] > 1else0 dp[i + 1][j] += cur dp[i + 1][j + 1] += cur returnmin(dp[query_row][query_glass], 1)
另一种写法:
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defchampagneTower(self, poured, query_row, query_glass): """ :type poured: int :type query_row: int :type query_glass: int :rtype: float """ dp = [[0for _ inrange(query_row + 1)] for i inrange(query_row + 1)] dp[0][0] = poured for i inrange(1, query_row + 1): for j inrange(i + 1): dp[i][j] += (max(dp[i - 1][j - 1] - 1, 0) / 2.0) + (max(dp[i - 1][j] - 1, 0) / 2.0) returnmin(dp[query_row][query_glass], 1)
818. Race Car
Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.)
Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).
When you get an instruction "A", your car does the following: position += speed, speed *= 2.
When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1. (Your position stays the same.)
For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1.
Now for some target position, say the length of the shortest sequence of instructions to get there.
Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3.
Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.