当前位置:   article > 正文

LeetCode 之动态规划_given two words word1 and word2, find the minimum

given two words word1 and word2, find the minimum number of steps required t

1. Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

一维动态规划,从左到右扫描

  1. bool canJump1(int A[], int n){
  2. int maxCover = 0;
  3. for(int start = 0; start<=maxCover && start<n;start++){
  4. if(A[start]+start > maxCover)
  5. maxCover = A[start]+start;
  6. if(maxCover >=n-1)
  7. return true;
  8. }
  9. return false;
  10. }

方法二:

直接实现,len记录当前Jump距离,大于等于n-1时返回true

  1. bool canJump(int A[], int n) {
  2. int len = 0;
  3. int *p = A;
  4. while(len<n){
  5. int dis = *p;
  6. if(dis == 0 && len < n-1)
  7. return false;
  8. len+=dis;
  9. if(len == n-1 || (len== n && dis == len))
  10. return true;
  11. p += dis;
  12. }
  13. return true;
  14. }

2 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。 Step[i][j] = Step[i-1][j] + Step[i][j-1];

  1. int uniquePaths(int m, int n) {
  2. vector <int> maxpath(n,0);
  3. maxpath[0] = 1;
  4. for(int i=0; i<m;i++){
  5. for(int j=1; j<n;j++){
  6. maxpath[j] = maxpath[j-1]+maxpath[j];
  7. }
  8. }
  9. return maxpath[n-1];
  10. }


3.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.

和Unique Path一样的转移方程:
Step[i][j] = Step[i-1][j] + Step[i][j-1] if Array[i][j] ==0
or = 0 if Array[i][j] =1


  1. int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
  2. int m = obstacleGrid.size();
  3. if(m==0) return 0;
  4. int n = obstacleGrid[0].size();
  5. if(obstacleGrid[0][0] == 1) return 0;
  6. vector<int> maxpath(n,0);
  7. maxpath[0] = 1;
  8. for(int i=0; i< m; i++){
  9. for(int j=0;j<n;j++){
  10. if(obstacleGrid[i][j] == 1)
  11. maxpath[j] = 0;
  12. else if(j>0)
  13. maxpath[j] = maxpath[j]+maxpath[j-1];
  14. }
  15. }
  16. return maxpath[n-1];
  17. }

4. Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

利用动态规划的思路。dp[i][j]表示word1的前i个字母与word2的前j个字母的编辑距离。
1)若word1[i+1]==word2[j+1] dp[i+1][j+1] = dp[i][j];否则,dp[i+1][j+1] = dp[i][j] + 1。(利用替换原则)
2)dp[i+1][j+1]还可以取dp[i][j+1]与dp[i+1][j]中的较小值。(利用删除添加原则)

总结的递推公式就是:

dp[j][i] = min(distance[j][i - 1] + insert, distance[j - 1][i] + delete, distance[j - 1][i - 1] + replace);

其中replace需要判断一下
实际dp[i+1][j+1]应当取上述两种情况的较小值。

  1. int minDistance(string word1, string word2) {
  2. int s1 = word1.size();
  3. int s2 = word2.size();
  4. if(s1 == 0)
  5. return s2;
  6. if(s2 == 0)
  7. return s1;
  8. vector<int> *dp = new vector<int>[s2+1];
  9. for(int i=0;i<=s1;i++)
  10. dp[0].push_back(i);
  11. for(int i=0;i<=s2;i++)
  12. dp[i].push_back(i);
  13. for(int i=1;i<=s2;i++){
  14. for(int j=1;j<=s1;j++){
  15. int n1 = word2[i-1]!=word1[j-1]?(dp[i-1][j-1]+1):dp[i-1][j-1];
  16. int n2 = dp[i-1][j]<dp[i][j-1]?(dp[i-1][j]+1):(dp[i][j-1]+1);
  17. dp[i].push_back(n1<n2? n1:n2);
  18. }
  19. }
  20. return dp[s2][s1];
  21. }

5.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. int maxProfit(vector<int> &prices) {
  2. int max=0, minV = INT_MAX;
  3. int diff;
  4. for(int i=0; i<prices.size();i++){
  5. if(prices[i]<minV) minV = prices[i];
  6. diff = prices[i]-minV;
  7. if(diff > max)
  8. max = diff;
  9. }
  10. return max;
  11. }

6.Best Time to Buy and Sell Stock II

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

从左到右扫面,记录所有差值为正的数据,之和为最大盈利

  1. int maxProfit2(vector<int> &prices){
  2. int sum = 0;
  3. for(int i=1;i<prices.size();i++){
  4. if(prices[i]-prices[i-1] > 0)
  5. sum+= prices[i]-prices[i-1];
  6. }
  7. return sum;
  8. }

7. Best Time to Buy and Sell stock III

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

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

MaxPro[0,n] = max(MaxPro[0,i]+MaxPro[i+1,n]);

最多只能交易两次。

两种情况,

1.从左到右只有一个股票上升的区间

2. 从左到右有多个股票上升区间,MaxPro[0,n] = max(MaxPro[0,i]+MaxPro[i+1,n]);

两个数组,一个记录从左到右扫描的每个位置的盈利值,一个记录从右到左扫描的每个位置的盈利值。

最后通过取maxFromLeft[i] maxFromRight[i+1]实现MaxPro[0,n] = max(MaxPro[0,i]+MaxPro[i+1,n]);

  1. int maxProfit(vector<int> &prices){
  2. if(prices.size()<=1) return 0;
  3. if(prices.size()==2) return prices[1]>prices[0]?prices[1]-prices[0]:0;
  4. vector<int> maxFromLeft(prices.size(),0);
  5. vector<int> maxFromRight(prices.size(),0);
  6. int minL = INT_MAX, max=INT_MIN, diff;
  7. for(int i=0;i<prices.size();i++){
  8. if(prices[i]<minL) minL = prices[i];
  9. diff = prices[i]- minL;
  10. if(diff >max)
  11. max = diff;
  12. maxFromLeft[i] = max;
  13. }
  14. int maxR = INT_MIN;
  15. max = INT_MIN;
  16. for(int i=prices.size()-1;i>=0;i--){
  17. if(prices[i]>maxR) maxR = prices[i];
  18. diff = maxR - prices[i];
  19. if(diff > max)
  20. max = diff;
  21. maxFromRight[i] = max;
  22. }
  23. max = INT_MIN;
  24. for(int i=0;i<prices.size()-1;i++){
  25. int diff = maxFromLeft[i]+maxFromRight[i+1];
  26. if(diff > max) max = diff;
  27. }
  28. if(max < maxFromRight[0])
  29. max = maxFromRight[0];
  30. return max;
  31. }


8. Restore IP address

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


This problem can be viewed as a DP problem. There needed 3 dots to divide the string, and make sure the IP address is valid:  less than or equal to 255, greater or equal to 0, and note that, "0X" or "00X" is not valid.
For the DP, the length of each part is from 1 to 3. We use a vector<string> to store each part, and cut the string every time. Details see the code.

  1. /*
  2. s -- string, input
  3. start -- startindex, start from which index in s
  4. step -- step current step index, start from 0, valid value1-4,4 means the end
  5. ip -- intermediate, split result in current spliting process
  6. result -- save all possible ip address
  7. */
  8. void dfsIp(string s, size_t start, size_t step, string ip,
  9. vector<string> &result){
  10. if(start == s.size() && step == 4){//find a possible result
  11. ip.resize(ip.size()-1);
  12. result.push_back(ip);
  13. return;
  14. }
  15. //since each part of IP address is in 0..255,the leagth of each
  16. // part is less than 3 and more than 0
  17. if(s.size()-start > (4-step)*3) return;
  18. if(s.size()-start < (4-step)) return;
  19. int num=0;
  20. for(size_t i=start;i<start+3;i++){
  21. num = num*10 + (s[i]-'0');
  22. if(num<=255){
  23. ip+=s[i];
  24. dfsIp(s,i+1,step+1,ip+'.',result);
  25. }
  26. if(num == 0) break;
  27. }
  28. }
  29. vector<string> restoreIpAddresses(string s) {
  30. vector<string> result;
  31. string ip; // save temporaty result in processing
  32. dfsIp(s,0,0,ip,result);
  33. return result;
  34. }

9.Climbing a stair

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?

DP. The transition function should be:
 f(n) = f(n-1) + f(n-2)  n>2;
     or = 1   n=1
    or  = 2   n=2

  1. int climbStairs(int n) {
  2. if(n==0) return 0;
  3. if(n==1) return 1;
  4. if(n==2) return 2;
  5. int fn=0, fn_1 = 1,fn_2=2;
  6. for(int i=3;i<=n;i++){
  7. fn = fn_2+fn_1;
  8. fn_1 = fn_2;
  9. fn_2 = fn;
  10. }
  11. return fn;
  12. }



10. 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.

Similar as " [LeetCode] Climbing Stairs". DP. Just add some logic to compare character.

Transformation function as:
Count[i] = Count[i-1]  if S[i-1] is a valid char
       or   = Count[i-1]+ Count[i-2]  if S[i-1] and S[i-2] together is still a valid char.


  1. int check(char one){
  2. return (one != '0') ? 1:0;
  3. }
  4. int check(char one, char two){
  5. return (one =='1' || (one=='2'&& two<='6'))?1:0;
  6. }
  7. int numDecodings(string s) {
  8. if(s.empty() || s[0]=='0') return 0;
  9. if(s.size()==1) return check(s[0]);
  10. int fn=0, fn_1 = 0,fn_2 = 1;
  11. fn_1 = (check(s[0])*check(s[1]))+check(s[0],s[1]);
  12. for(int i=2;i<s.size();i++){
  13. if(check(s[i])) fn+=fn_1;
  14. if(check(s[i-1],s[i])) fn+=fn_2;
  15. if(fn == 0)
  16. return 0;
  17. fn_2 = fn_1;
  18. fn_1 = fn;
  19. fn = 0;
  20. }
  21. return fn_1;
  22. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/577203
推荐阅读
相关标签
  

闽ICP备14008679号