问题:
种花问题,在给出的花圃中(可能已经种植了一些花),如果存在空位与其他花相隔1个空位,则可在此处种植。
求:给出的花圃中,能否种植完给定数量的花。
Input: flowerbed = [1,0,0,0,1], n = 1 Output: True
Input: flowerbed = [1,0,0,0,1], n = 2 Output: False
如上给出的花圃中,只有下述种植方法
[1,0,0,0,1] ^ -> [1,0,1,0,1]
解决方法:
1.可种植的条件:
a. 该位置=0
b. 该位置前,后=0
注意:边界:第一位置【只要求后=0】最后一个位置【只要求前=0】
代码参考:
1 class Solution { 2 public: 3 bool canPlaceFlowers(vector<int>& flowerbed, int n) { 4 int count = 0; 5 for(int i=0; i < flowerbed.size(); i++){ 6 if(count == n) return true; 7 if(flowerbed[i] == 0){ 8 int pre = (i==0? 0:flowerbed[i-1]); 9 int nex = (i==flowerbed.size()-1?0:flowerbed[i+1]); 10 if(pre==0 && nex==0){ 11 flowerbed[i] = 1; 12 count++; 13 } 14 } 15 } 16 return count>=n; 17 } 18 };