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;
}
}