leetcode-Candy
2014-09-25 16:52
309 查看
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?
class Solution {
public:
int allocate (vector<int> &r, vector<int> &a, int i, int &n)
{
if(a[i] != 0)return a[i];
int m = 0;
if(i > 0 && r[i] > r[i-1]) m = allocate(r,a,i-1,n);
if(i < n-1 && r[i] > r[i+1]) m =max(m,allocate(r,a,i+1,n));
a[i] = m+1;
return a[i];
}
int candy(vector<int> &ratings) {
int n = ratings.size();
if(n == 0)return 0;
if(n == 1)return 1;
vector<int> nums(n,0);
int ret = 0;
if(ratings[0] < ratings[1]) nums[0] = 1;
if(ratings[n-1] < ratings[n-2]) nums[n-1] = 1;
for(int i = 1; i < n-1; i++)
{
if(ratings[i] < ratings[i-1]&&ratings[i] < ratings[i+1])
{
nums[i] = 1;
}
}
for(int i = 0; i < n; i++)
{
if(nums[i] == 0)
{
(void)allocate(ratings,nums,i,n);
}
}
for(int i = 0; i < n; i++)
{
ret += nums[i];
}
return ret;
}
};
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?
class Solution {
public:
int allocate (vector<int> &r, vector<int> &a, int i, int &n)
{
if(a[i] != 0)return a[i];
int m = 0;
if(i > 0 && r[i] > r[i-1]) m = allocate(r,a,i-1,n);
if(i < n-1 && r[i] > r[i+1]) m =max(m,allocate(r,a,i+1,n));
a[i] = m+1;
return a[i];
}
int candy(vector<int> &ratings) {
int n = ratings.size();
if(n == 0)return 0;
if(n == 1)return 1;
vector<int> nums(n,0);
int ret = 0;
if(ratings[0] < ratings[1]) nums[0] = 1;
if(ratings[n-1] < ratings[n-2]) nums[n-1] = 1;
for(int i = 1; i < n-1; i++)
{
if(ratings[i] < ratings[i-1]&&ratings[i] < ratings[i+1])
{
nums[i] = 1;
}
}
for(int i = 0; i < n; i++)
{
if(nums[i] == 0)
{
(void)allocate(ratings,nums,i,n);
}
}
for(int i = 0; i < n; i++)
{
ret += nums[i];
}
return ret;
}
};
相关文章推荐
- candy leetcode
- 【Leetcode】Candy
- 【leetcode】candy
- LeetCode | Candy(分糖果问题)
- leetcode-candy
- 【LeetCode】Candy
- leetcode-Candy(2014.2.25)
- Leetcode 之Candy 分糖果问题。
- (LeetCode 135) Candy N个孩子站成一排,给每个人设定一个权重
- LeetCode——Candy
- [LeetCode] Candy
- Leetcode (135) Candy
- 6 Candy_Leetcode
- Leetcode 动态规划 Candy
- LeetCode:Candy
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- [leetcode] Candy
- [Leetcode] Candy
- [LeetCode]Candy
- LeetCode:Candy