欢迎来到Cefler的博客😁
🕌博客主页:那个传说中的man的主页
🏠个人专栏:题目解析
🌎推荐文章:【LeetCode】winter vacation training
目录
- 👉🏻按摩师
- 👉🏻打家劫舍I
- 👉🏻打家劫舍II
👉🏻按摩师
原题链接:按摩师
mycode:
class Solution {
public:int massage(vector<int>& nums) {int n = nums.size();vector<int> f(n),g(n);//考虑越界情况if(n==0) return 0;//初始化f[0] = nums[0],g[0] = 0;for(int i = 1;i<n;i++){f[i] = g[i-1]+nums[i];g[i] = max(f[i-1],g[i-1]);}return max(f[n-1],g[n-1]);}
};
👉🏻打家劫舍I
原题链接:打家劫舍I
mycode:
class Solution {
public:int rob(vector<int>& nums) {int n = nums.size();vector<int> f(n),g(n);//偷或不偷两种状态//初始化f[0] = nums[0],g[0] = 0;for(int i = 1;i<n;i++){f[i] = g[i-1]+nums[i];g[i] = max(f[i-1],g[i-1]);}return max(f[n-1],g[n-1]);}
};
👉🏻打家劫舍II
原题链接:打家劫舍II
mycode:
class Solution {
public:int rob1(vector<int>& nums,int left,int right){if(left>right) return 0;int n = nums.size();vector<int> f(n),g(n);f[left] = nums[left];for(int i = left+1;i<=right;i++){f[i] = g[i-1]+nums[i];g[i] = max(f[i-1],g[i-1]);}return max(f[right],g[right]);}int rob(vector<int>& nums) {int n = nums.size();return max(nums[0]+rob1(nums,2,n-2),rob1(nums,1,n-1));}
};