Can Place Flowers问题及解法
来源:互联网 发布:网络文凭国家承认吗 编辑:程序博客网 时间:2024/05/16 18:05
问题描述:
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
示例:
Input: flowerbed = [1,0,0,0,1], n = 1Output: True
Input: flowerbed = [1,0,0,0,1], n = 2Output: False问题分析:
每种一棵花,都需要保证它的前后都没有种过花。这里将数组前后分别加入一个元素0,以便于求解。
过程详见代码:
class Solution {public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { if (n == 0) return true;flowerbed.push_back(0);flowerbed.insert(flowerbed.begin(), 0);for (int i = 1; i < flowerbed.size() - 1;i++){if (flowerbed[i] == 0 && flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0){flowerbed[i] = 1;n--;if (n == 0)return true;}}return false; }};
阅读全文
0 0
- Can Place Flowers问题及解法
- LeetCode 605. Can Place Flowers 自己的解法
- 605. Can Place Flowers
- Can Place Flowers
- 605. Can Place Flowers
- 605Can Place Flowers
- 605. Can Place Flowers
- leetcode605. Can Place Flowers
- 605. Can Place Flowers
- 605. Can Place Flowers
- 605. Can Place Flowers
- Can Place Flowers
- leetcode[Can Place Flowers]
- 605. Can Place Flowers
- Can Place Flowers
- 605. Can Place Flowers
- leetcode-Can Place Flowers
- Can Place Flowers
- Linux服务器入侵检测常用命令
- exercise6
- Oracle子查询实例
- 类似jQuery的extend扩展方法的实现
- CentOS7.0修改主机名(hostname)
- Can Place Flowers问题及解法
- argument.callee 指向函数本身
- 偶串问题-牛客三模
- springboot+mybatis显示sql语句
- POJ-1308-Is It A Tree? [并查集]
- 漫水填充算法
- 转换PDF技巧1之PDF虚拟打印机操作详解
- 嵌入式学习书籍推荐
- js网页简易计算器