您的位置:首页 > 其它

LeetCode: Candy

2014-08-23 13:57 239 查看
[b]LeetCode: Candy[/b]

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

Each child must have at least one candy.

Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

地址:https://oj.leetcode.com/problems/candy/

算法:这道题用动态规划可以解决,之前在王道的练习赛上有遇到过,分析见我之前的一篇文章:/article/6286416.html

代码:

class Solution {
public:
int candy(vector<int> &ratings) {
int n = ratings.size();
vector<int> num_candys(n);
if(n == 0)
return 0;
return subSolution(0,n-1,num_candys,ratings);
}
int subSolution(int s, int e, vector<int> &num_candys,vector<int> &ratings){
if(s == e){
num_candys[s] = 1;
return 1;
}else{
int total = 0;
int mid = (s + e) >> 1;
int left = subSolution(s,mid,num_candys,ratings);
int right = subSolution(mid+1,e,num_candys,ratings);
if(ratings[mid] == ratings[mid+1]){
return left + right;
}else if(ratings[mid] > ratings[mid+1]){
if(num_candys[mid] > num_candys[mid+1])
return left + right;
else{
total += (num_candys[mid+1] + 1 - num_candys[mid]);
num_candys[mid] = num_candys[mid+1] + 1;
int totalAdd = 0;
for(int i = mid-1; i >= s; --i){
if(ratings[i] <= ratings[i+1] || (ratings[i] > ratings[i+1] && num_candys[i] > num_candys[i+1]))
break;
else{
total += (num_candys[i+1] + 1 - num_candys[i]);
num_candys[i] = num_candys[i+1] + 1;
}
}
return left + right + total;
}
}else{
if(num_candys[mid] < num_candys[mid+1])
return left + right;
else{
total += (num_candys[mid] + 1 - num_candys[mid+1]);
num_candys[mid+1] = num_candys[mid] + 1;
for(int i = mid+2; i <= e; ++i){
if(ratings[i] <= ratings[i-1] || (ratings[i] > ratings[i-1] && num_candys[i] > num_candys[i-1]))
break;
else{
total += (num_candys[i-1] + 1 - num_candys[i]);
num_candys[i] = num_candys[i-1] + 1;
}
}
return left + right + total;
}
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: