classSolution{public:intcherryPickup(vector<vector<int>>&grid){int n = grid.size();
vector<vector<vector<int>>>f(n *2-1,vector<vector<int>>(n,vector<int>(n, INT_MIN)));
f[0][0][0]= grid[0][0];for(int k =1; k < n *2-1;++k){for(int x1 =max(k - n +1,0); x1 <=min(k, n -1);++x1){int y1 = k - x1;if(grid[x1][y1]==-1){continue;}for(int x2 = x1; x2 <=min(k, n -1);++x2){int y2 = k - x2;if(grid[x2][y2]==-1){continue;}int res = f[k -1][x1][x2];// 都往右if(x1){
res =max(res, f[k -1][x1 -1][x2]);// 往下,往右}if(x2){
res =max(res, f[k -1][x1][x2 -1]);// 往右,往下}if(x1 && x2){
res =max(res, f[k -1][x1 -1][x2 -1]);// 都往下}
res += grid[x1][y1];if(x2 != x1){// 避免重复摘同一个樱桃
res += grid[x2][y2];}
f[k][x1][x2]= res;}}}returnmax(f.back().back().back(),0);}};
873. 最长的斐波那契子序列的长度(二刷)
代码实现(二刷自解)
classSolution{public:intlenLongestFibSubseq(vector<int>& arr){
unordered_map<int,int> myMap;int n = arr.size();for(int i =0; i < n; i++){
myMap[arr[i]]= i;}
vector<vector<int>>dp(n,vector<int>(n,0));int ans =0;for(int i =1; i < n; i++){for(int j = i +1; j < n; j++){int firstNum = arr[j]- arr[i];if(firstNum >= arr[i])continue;if(myMap.count(firstNum)){int index = myMap[firstNum];
dp[j][i]=max(dp[i][index]+1,3);
ans =max(dp[j][i], ans);}}}return ans;}};
1760. 袋子里最少数目的球(132)
代码实现(看题解)
classSolution{public:intminimumSize(vector<int>& nums,int maxOperations){int l =0;int r =*max_element(nums.begin(), nums.end())+1;while(l +1!= r){int m = l + r >>1;int pos =0;for(int num : nums){
pos +=(num -1)/ m;}if(pos <= maxOperations) r = m;else l = m;}return r;}};