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)
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;
}