以下面这个题为例:
动态规划:暴力穷举所有的可能
贪心算法:在每一个子问题中选择最优解
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
private:
vector<int> memo;
public:
int jump(vector<int>& nums) {
int n = nums.size();
memo = vector<int>(n, n);
return dp(nums, 0);
}
/*
*利用动态规划来解决
*/
int dp(vector<int>& nums, int p) {
int n = nums.size();
//子问题
if (p >= n - 1) return 0;
if (memo[p] != n) return memo[p];
int step = nums[p];
for (int i = 1; i <= step; ++i) {
//穷举每一个选择
int subProble = dp(nums, p + i);
memo[p] = min(memo[p], subProble + 1);
}
return memo[p];
}
/*
*利用贪心算法来解决
*/
int jump1(vector<int>& nums) {
int n = nums.size();
int end = 0, farthest = 0;
int jump = 0;
for (int i = 0; i < n - 1; ++i) {
farthest = max(i + nums[i], farthest);
if (end == i) {
jump++;
end = farthest;
}
}
return jump;
}
};
int main() {
vector<int> a = { 2,3,1,1,4 };
Solution k;
//int res = k.jump(a);
int res = k.jump1(a);
cout << res << endl;
system("pause");
return 0;
}
参考文献在此!!!