LeetCode Learning 6

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?

本题难度为medium。题目大意为给出mxn的方格区域,从左上角只能往右或下走,求出走到右下角路径的数量。

方法一:可以利用动态规划的思想,path[i][j]为ixj时的走法,i=1或j=1时显然值为1。其余的就可以通过公式:path[i][j]=path[i-1][j]+path[i][j-1];即可得出path[m-1][n-1]的最终结果。代码如下:

int uniquePaths(int m, int n) {
        int paths[m][n];
         for(int i = 0; i < m; ++i)  paths[i][0] = 1;  
          
        for(int j = 0; j < n; ++j)  paths[0][j] =1;  
  
        for(int i = 1; i < m; ++i)  
            for(int j = 1; j < n; ++j)  
            {  
                paths[i][j] = paths[i-1][j]+paths[i][j-1]; 
            }  
            
        return paths[m-1][n-1];
    }
方法二:本题其实可以转化为一个从m+n-2步中,选出m-1的向右步数或n-1的向下步数的数学问题,即只需求出C(m+n-2,m-1)。代码如下:

int uniquePaths(int m, int n) {
        if(m==1||n==1)return 1;
        long long int i,j,a,b,sum=1;
        a=m+n-2;
        if(m>n)  b=n-1;
        else b=m-1;
    for (i=a,j=0;j<b;j++,i--)
    {
        sum=sum*i/(j+1);
    }
    return int(sum);
    }

309. Best Time to Buy and Sell Stock with Cooldown

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) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
难度为medium。题目大意为给出i天的股价,每天可以买入或卖出,重新买入前必须卖出,且卖出后的一天为CD时间无法买入。这题仍然是利用动态规划。生成3个数组, buy[i]表示在第i天之前最后一个操作是买,此时的最大收益。 sell[i]表示在第i天之前最后一个操作是卖,此时的最大收益。 rest[i]表示在第i填之前最后一个操作是冷冻期,此时的最大收益。根据题意可以得出公式:

sell[i] = max(sell[i-1], buy[i-1] + price[i]); buy[i] = max(buy[i-1], sell[i-2] - price[i]);

进一步优化,由于sell[i]只需要前2项的数据,不需要生成数组,只要保持2项的buy和sell即可,这样得出的具体代码如下:

int maxProfit(vector<int> &prices)
        {
            int buy = INT_MIN;
            int pre_buy = 0;
            int sell = 0;
            int pre_sell = 0;
            for (int i = 0; i < prices.size(); i++)
            {
                pre_buy = buy;
                buy = max(pre_sell - prices[i], pre_buy);
                pre_sell = sell;
          sell = max(pre_buy + prices[i], pre_sell);
            }
            return sell;
        }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值