🔥 LeetCode 热题 HOT 100 : 39 && 42

120 阅读2分钟

“Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。”

39. 组合总和

一、题目描述:

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7 输出:[[2,2,3],[7]] 解释: 2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。 7 也是一个候选, 7 = 7 。 仅有这两种组合。

二、思路分析:

  • 回溯, 遍历所有的可能, 主要考虑3点
  1. 结束的条件(index 到达数组末尾 || 当前路径和为 target)
  2. 可以做出的选择(index 位置的数字可选 可不选)
  3. 记录已经做出的选择(path)

三、AC 代码:

class Solution {

    List<List<Integer>> ans;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.ans = new ArrayList<>();
        dfs(candidates, 0, new ArrayList<>(), target);
        return ans;
    }

    void dfs(int[] candidates, int index, List<Integer> path, int target){
        if(target == 0){
            ans.add(new ArrayList<>(path));
            return;
        }

        if(index == candidates.length) return;

        dfs(candidates, index + 1, path, target);

        if(candidates[index] <= target){
            path.add(candidates[index]);
            dfs(candidates, index, path, target - candidates[index]);
            path.remove(path.size() - 1);
        }
    }
}

42. 接雨水

一、题目描述:

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

image.png

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1] 输出:6 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

二、思路分析:

index 位置的接水量取决于 左右两边柱子最大中较小的高度, 木桶理论

  • 朴素解法, 遍历, 记录每个 index 位置 左右的最大值
  • 双指针, 维护左右两边的最大高度, 到 左边的最大值 小于右边的最大值时, 当前 index 的接水量就是 leftMax - height[index], 遍历累加即可

三、AC 代码:

class Solution {
    public int trap(int[] height) {
        int l = 0, r = height.length - 1;
        int lMax = 0, rMax = 0;

        int ans = 0;
        while(l <= r){
            lMax = Math.max(lMax, height[l]);
            rMax = Math.max(rMax, height[r]);

            if(lMax <= rMax){
                ans += (lMax - height[l]);
                l++;
            }else{
                ans+= (rMax - height[r]);
                r--;
            }
        }
        return ans;
    }
}