Problem P20. [算法课蛮力法]种花问题
我写的并不好,力扣上有比这更好的方法
我的思路:从头遍历数组,检查位置是否能放下花,能放就放下,然后检查下一个位置,注意放下之后就改变了数组。然后就是注意前后数组越界,注意数组只有一个数时的情况。
#include<iostream>
#include<bits/stdc++.h>
#include<cstdio>
#include<string>
using namespace std;
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int num = 0;
if (flowerbed.size() == 1){
if (flowerbed[0] == 0 && n < 2 || n == 0){
return true;
}else {
return false;
}
}
for (int i = 0; i < flowerbed.size(); i++){
//cout << i << endl;
if (flowerbed[i] == 0){
if (i == 0 && flowerbed[1] == 0){
flowerbed[i] = 1;
num++;
}else if (i != 0 && flowerbed[i-1] == 0){
if (i == flowerbed.size()-1){
flowerbed[i] = 1;
num++;
}else if (flowerbed[i+1] == 0){
flowerbed[i] = 1;
num++;
}
}
}
}
if (num >= n){
return true;
}else {
return false;
}
}
};
int main()
{
vector<int> flowerbed;
int n;
while(true){
int c;
int ret = scanf("%d", &c);
if (ret == EOF){
break;
}
flowerbed.push_back(c);
}
n = flowerbed[flowerbed.size()-1];
flowerbed.pop_back();
Solution* so = new Solution();
if (so->canPlaceFlowers(flowerbed, n)==true){
cout << "true";
}else {
cout << "false";
}
return 0;
}