0
点赞
收藏
分享

微信扫一扫

LeetCode题解:2079. 给植物浇水

浮游图灵 2022-04-02 阅读 25

文章目录


遇到不会的多想想,又不是做不出来,别总问别人。实在不行…
在这里插入图片描述

题目

1、题目描述

2、原题链接

给植物浇水

解题报告

1、解题思路

在这里插入图片描述
  (1)这种题首先可以想到的是前缀和。
  (2)当前植物浇水的步数与之前已经浇水的步数之和为从开始到现在的总步数。
  (3)如果当前植物所需水量 > > > 水壶中剩余水量那么就回去灌水再浇。所需步数为: 2 ∗ x + 1 2 * x + 1 2x+1
  (4)如果当前植物所需水量 ≤ \le 水壶中剩余水量。步数加一。
  (5)更新水壶中水的量。

2、解题方法

  DFS

2、代码详解

int dfs(int cap, int* plants, int plantsSize, int step, int capacity){
    if(plantsSize == step){
        return 0;
    }
    int ans = 0;
    int Cap = cap;
    if(plants[step] > cap){
        ans += step*2 + 1;
        Cap = capacity - plants[step];
    }else{
        ++ans;
        Cap -= plants[step];
    }
    ++step;
    return ans + dfs(Cap, plants, plantsSize, step, capacity);
}

int wateringPlants(int* plants, int plantsSize, int capacity){
    return dfs(capacity, plants, plantsSize, 0, capacity);
}

总结

  一般来说像这种的数据都可以用前缀和来做。
  也可以先将数据状态压缩后考虑是否可以用前缀和。

举报

相关推荐

0 条评论