实现代码: #include <iostream>#include<vector>usingnamespacestd;classSolution {public:intcandy(vector<int> &ratings) {intlen =ratings.size();if(len ==0|| len ==1)returnlen;int*c =newint[len]; c[0] =1;for(inti =1; i < len; i++)if(ratings[i] > ratings[i-1]) c[i]= c[...
Leetcode solution 135: Candy Blogger:https://blog.baozitraining.org/2019/11/leetcode-solution-135-candy.html 博客园: https://www.cnblogs.com/baozitraining/p/11747009.html B站: https://www.bilibili.com/video/av73575024/ Problem Statement There are N children standing in a line. Each child...
https://discuss.leetcode.com/topic/5243/a-simple-solution https://discuss.leetcode.com/topic/8208/one-pass-constant-space-java-solution https://discuss.leetcode.com/topic/17722/two-c-solutions-given-with-explanation-both-with-o-n-time-one-with-o-1-space-the-other-with-o-n-space LeetCod...
第一种解法使用两次遍历方式,先从左向右遍历确保右侧评分更高的孩子获得更多糖果,再从右向左遍历确保左侧评分更高的孩子获得更多糖果。 classSolution{publicintcandy(int[]ratings){intn=ratings.length;int[]candies=newint[n];Arrays.fill(candies,1);for(inti=1;i<n;i++){if(ratings[i]>ratings[i-1])...
不过本题也加了其他限制,所以我们可以自定顺序,即可以通过rating 从小到大的顺序处理,来进行状态转移,这种处理方法与 LeetCode 329 一致。 如果我们按照 rating 从小到大的顺序进行状态转移,所有 ratings[j] 小于 ratings[i] 的 dp[j] 都已确定,所以 dp[i] 就能通过两边的的 dp 值转移得到。
public class Solution { public int candy(int[] ratings) { if(ratings.length < 1){ return 0; } int len = ratings.length; int[] dpLeft = new int[len]; int[] dpRight = new int[len]; int[] res = new int[len]; int sum = 0; dpLeft[0] = 1; dpRight[len - 1] = 1; /...
题目链接:https://leetcode.com/problems/candy/ 老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。 你需要按照以下要求,帮助老师给这些孩子分发糖果: 每个孩子至少分配到 1 个糖果。 相邻的孩子中,评分高的孩子必须获得更多的糖果。 那么这样下来,老师至少需要准备多...
https://leetcode.com/problems/candy-crush/solution/classSolution {publicint[][] candyCrush(int[][] board) {intR = board.length, C = board[0].length;booleantodo =false;//reset//horizontal scanfor(intr = 0; r < R; ++r) {for(intc = 0; c + 2 < C; ++c) {intv =Math.abs(bo...
1. 2. 3. 4. 5. 6. 7. 8. 解析 这样前后两个遍历结果,思路 采用一次遍历实现或者其他动态规划的思路实现 class Solution_135 { //题意:N个孩子站成一排,每个孩子分配一个分值。给这些孩子派发糖果,满足如下要求: //每个孩子至少一个 //分值更高的孩子比他的相邻位的孩子获得更多的糖果 ...
classSolution(object):defcandy(self,ratings):""" :type ratings: List[int] :rtype: int """dp=[1foriinrange(len(ratings))]foriinrange(1,len(ratings)):ifratings[i]>ratings[i-1]anddp[i]<=dp[i-1]:dp[i]=dp[i-1]+1foriinrange(len(ratings)-2,-1,-1):ifratings[i]>ratings[...