Approach For Dynamic progaming
Basic Concept
动态规划算法通过拆分问题,定义问题状态和状态之间的关系,使得问题能够以递推的方式去解决。
与分治法不同的是,通常将待求解的问题分解为互相影响的若干个子问题(阶段),按顺序求解子阶段,前一子问题的解,为后一子问题的求解提供了有用的信息。在求解任一子问题时,列出各种可能的局部解,通过决策保留那些有可能达到最优的局部解,丢弃其他局部解。依次解决各子问题,最后一个子问题就是初始问题的解。
Key Point
采用动态规划算法最关键的点在于,找到状态转移方程,将一个子问题分解,然后子问题最优解也是当前问题最优解的一部分。要通过归纳总结的方法找到子问题之间的关联节点,然后实现转换。
Application
Problem1
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.
Ex1
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
EX2
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
Ananlysis
状态方程为,
设T[i]是第i天之后的价格中最大的数,
T[i]=min
{
prices[i],T[i+1]
}
然后用T[i]减去当前的价格,如果比当前的最大价差还要大,就更新最大价差,否则不变。
复杂度分析
空间复杂度:
O(n)
时间复杂度:
O(n)
code
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n == 0) return 0;
if (n == 1) return 0;
int* T = new int[n];
T[n-1] = prices[n-1];
int max = 0;
for (int i = n - 2; i >= 0; i--) {
if (T[i+1] > prices[i]) {
if (max < (T[i+1]-prices[i])) {
max = T[i+1]-prices[i];
}
T[i] = T[i+1];
} else {
T[i] = prices[i];
}
}
delete []T;
return max;
}
};
problem2
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
具体请见Leetcode
Anaysis
这是一道个人感觉还是蛮复杂的题,首先要分析清楚,它能完成三种操作,每一个对于前面一个来说有插入,删除,和替换。对于当前的状态,记为E(i,j),它可以由前面三个子问题得来。状态方程可写为:
E(i,j)=min
{
E(i−1,j)+1,E(i,j−1)+1,E(i−1,j−1)+diff(i−1,j−1)
}
其中
E(i−1,j)+1
表示删除一个字母,
E(i,j−1)+1
添加一个字母,
E(i−1,j−1)+diff(i−1,j−1)
表示不相同则替换,然后
E(i,j)
为三者中的操作最少值。
根据状态方程,可以写出代码:
code
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size() + 1;
int n = word2.size() + 1;
int** matrix = new int*[m];
for (int i = 0; i < m; i++) {
matrix[i] = new int[n];
}
for (int i = 0; i < m; i++) {
matrix[i][0] = i;
}
for (int j = 1; j < n; j++) {
matrix[0][j] = j;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
int diff = 0;
if (word1[i - 1] != word2[j - 1]) diff = 1;
matrix[i][j] = GetMin(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + diff);
}
}
int result = matrix[m - 1][n - 1];
for (int i = 0; i < m; i++) {
delete[]matrix[i];
}
delete[]matrix;
return result;
}
int GetMin(int a, int b, int c) {
int min = a;
if (min > b) min = b;
if (min > c) min = c;
return min;
}
};
复杂度分析
时间复杂度:
O(mn)
(遍历了一个
m×n
的二维数组)
空间复杂度:
O(mn)
(new了一个
m×n
的二维数组)