leetcode刷题计划Day8

200. 岛屿数量【中等】

https://leetcode-cn.com/problems/number-of-islands/
DFS 深度优先遍历
走过的格子要标记,不然会一直重复在走过的格子中,陷入死循环。(将值改为2)。

class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }

    private void dfs (char[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)
            return;
        if (grid[i][j] != '1')
            return;
        grid[i][j] = '2';
        dfs(grid, i-1, j);
        dfs(grid, i+1, j);
        dfs(grid, i, j-1);
        dfs(grid, i, j+1);
    }
}

46. 全排列【中等】

https://leetcode-cn.com/problems/permutations/
回溯算法DFS

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        dfs(nums, res, path, used);
        return res;
    }

    private void dfs(int[] nums, List<List<Integer>> res, List<Integer> path, boolean[] used) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue; 
            path.add(nums[i]);
            used[i] = true;
            dfs(nums, res, path, used);
            // 回溯时,将当前节点从path中删掉,并将uesd数组重新改回全false
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}

42. 接雨水【困难】

https://leetcode-cn.com/problems/trapping-rain-water/
动态规划
先遍历一遍 height [ i ] 每一位左边的最大高度,记录在left_max[]中,
再遍历一遍 height [ i ] 每一位右边的最大高度,记录在right_max[]中,
最后遍历一遍算出每一位的水位并相加。

class Solution {
    public int trap(int[] height) {
        if (height.length < 3) 
            return 0;
        int sum = 0;
        int[] lmax = new int[height.length];
        int[] rmax = new int[height.length];

        lmax[0] = height[0];
        rmax[height.length - 1] = height[height.length - 1];

        for (int i = 1; i < height.length; i++) {
            lmax[i] = Math.max(height[i], lmax[i - 1]);
        }
        for (int i = height.length - 2; i >= 0; i--) {
            rmax[i] = Math.max(height[i], rmax[i + 1]);
        }
        for (int i = 0; i < height.length; i++) {
            sum += Math.min(lmax[i], rmax[i]) - height[i];
        }
        return sum;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值