美文网首页
贪心--种花问题(easy)

贪心--种花问题(easy)

作者: warManHy | 来源:发表于2021-01-01 20:56 被阅读0次
    假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
    
    给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
    
    示例 1:
    
    输入: flowerbed = [1,0,0,0,1], n = 1
    输出: True
    示例 2:
    
    输入: flowerbed = [1,0,0,0,1], n = 2
    输出: False
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/can-place-flowers
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    

    思路:
    种花的条件
    自己为空
    左边为空 或者 自己是最左
    右边为空 或者 自己是最右

    1. 贪心 (跳格子+2,遍历)
    2. dp???
    class Solution(object):
        def canPlaceFlowers(self, flowerbed, n):
            """
            :type flowerbed: List[int]
            :type n: int
            :rtype: bool
            """
            f_len = len(flowerbed)
            for i in range(f_len):
                if (flowerbed[i]==0 and (i==0 or flowerbed[i-1]==0) and(i==f_len-1 or flowerbed[i+1] ==0)):
                    n -= 1
                    if n <= 0:
                        return True
                    flowerbed[i] = 1
            return n <= 0
    -------------------
    class Solution {
    public:
        bool canPlaceFlowers(vector<int>& flowerbed, int n) {
            // 每次跳两格
             for (int i = 0; i < flowerbed.size(); i += 2) {
                 // 如果当前为空地
                if (flowerbed[i] == 0) {
                    // 如果是最后一格或者下一格为空
                    if (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0) {
                        n--;
                    } else {
                        i++;
                    }
                }
            }
            return n <= 0;
        }
    };
    
    作者:heroding
    链接:https://leetcode-cn.com/problems/can-place-flowers/solution/qi-si-miao-jie-by-heroding-h7m0/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

    相关文章

      网友评论

          本文标题:贪心--种花问题(easy)

          本文链接:https://www.haomeiwen.com/subject/bytsoktx.html