79. Word Search

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

回溯,遍历所有初始元素。
当寻找的字符与当前matrix里的字符相同时,将当前位置记录在visited里,并向下递归搜索四个方向,回溯visited。
当越界或者字符已经visited时返回false。
当寻找到单词的最后一位时,如果当前matrix里的字符与搜索的字符相等,则返回true。反之返回false。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
char[][] bd;
String wd;
int[][] visited;
public boolean exist(char[][] board, String word) {
boolean ans = false;
visited = new int[board.length][board[0].length];
bd = board;
wd = word;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
ans = ans || backtracking(i, j, 0);
}
}
return ans;
}

private boolean backtracking(int i, int j, int n){

if(i < 0 || j < 0 || i >= bd.length || j >= bd[0].length || n >= wd.length()) return false;
if(visited[i][j] == 1) return false;
if(n == wd.length()-1) return bd[i][j] == wd.charAt(n);
if( bd[i][j] == wd.charAt(n) ){
n++;
visited[i][j] = 1;
boolean a = backtracking(i+1, j, n);
boolean b = backtracking(i-1, j, n);
boolean c = backtracking(i, j+1, n);
boolean d = backtracking(i, j-1, n);
visited[i][j] = 0;
return a || b || c || d;
}
return false;
}
}

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

回溯,记录左右括号的出现次数。
每次递归都添加左侧括号。
左侧括号的数量大于右侧括号时递归下一级才可以添加右侧括号。
当左侧括号和右侧括号达到n时,返回字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
int N;
List<String> ret;
StringBuffer sb;

public List<String> generateParenthesis(int n) {
ret = new ArrayList<>();
sb = new StringBuffer();
N = n;
backtracking(0, 0);
return ret;
}

private void backtracking(int left, int right){
if(left > N || right > N){
return;
}
if(left == N && right == N){
ret.add(sb.toString());
return;
}
if(left > right){
sb.append(')');
backtracking(left, right+1);
sb.delete(sb.length()-1, sb.length());
}
sb.append('(');
backtracking(left+1, right);
sb.delete(sb.length()-1, sb.length());
}
}

17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

回溯,每个回溯层级添加数字对应的字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public List<String> letterCombinations(String digits) {


List<String> ret = new ArrayList<>();
if(digits.equals("")) return ret;

char[][] bin = new char[8][0];
bin[0] = new char[]{'a', 'b', 'c'};
bin[1] = new char[]{'d', 'e', 'f'};
bin[2] = new char[]{'g', 'h', 'i'};
bin[3] = new char[]{'j', 'k', 'l'};
bin[4] = new char[]{'m', 'n', 'o'};
bin[5] = new char[]{'p', 'q', 'r', 's'};
bin[6] = new char[]{'t', 'u', 'v'};
bin[7] = new char[]{'w', 'x', 'y', 'z'};

backtracking(ret, new StringBuffer(), bin, digits, 0);
return ret;
}

private void backtracking(List<String> ret, StringBuffer sb, char[][] bin, String digits, int i){
if(sb.length() == digits.length() ){
ret.add(sb.toString());
return;
}

for(char c : bin[digits.charAt(i)-'2']){
sb.append(c);
backtracking(ret, sb, bin, digits, i+1);
sb.delete(sb.length()-1, sb.length());
}
}
}

2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

递归,每次递归时建立root的next节点,然后将root移动到root.next。
计算两个节点的和并填入root节点。每次计算时需要计算是否进位。
递归两个节点的next节点,并将carry传入。
当一个节点为null时,只递归和计算另一个节点。
当两个节点为null时,如果有carry需要将其放入新节点,如果没有则返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode();
addTwo(l1,l2,root,0);
return root.next;
}

private void addTwo(ListNode l1, ListNode l2, ListNode root, int carry){
if(l1 == null && l2 == null && carry == 0){
return;
}
else if(l1 == null && l2 == null){
root.next = new ListNode();
root = root.next;
root.val = carry;
return;
}
else if(l1 == null){
root.next = new ListNode();
root = root.next;
root.val = (l2.val + carry) % 10;
carry = (l2.val + carry) / 10;
addTwo(null, l2.next, root, carry);
return;
}
else if(l2 == null){
root.next = new ListNode();
root = root.next;
root.val = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
addTwo(null, l1.next, root, carry);
return;
}
root.next = new ListNode();
root = root.next;
root.val = (l1.val + l2.val + carry) % 10;
carry = (l1.val + l2.val + carry) / 10;

addTwo(l1.next, l2.next, root, carry);
}
}

40. Combination Sum II

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

由于有重复性元素,因此先将数组排序。
储存一个数组,记录元素是否被选择。
回溯,遍历选择元素,并计算加和,并记录选择的元素。当选择的元素与上一个元素重复时,则跳过。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ret = new ArrayList<>();
Arrays.sort(candidates);
backtracking(candidates, ret, new ArrayList<>(), new int[candidates.length], target, 0, 0);
return ret;
}

private void backtracking(int[] candidates, List<List<Integer>> ret, List<Integer> arr, int[] visited, int target, int sum, int level){
if(sum > target ){
return;
}
else if (sum == target){
ret.add(new ArrayList<>(arr));
return;
}

for(int i = level; i < candidates.length; i++){
if(i > 0 && candidates[i] == candidates[i-1] && visited[i-1] == 0) continue;
visited[i] = 1;
arr.add(candidates[i]);
sum+= candidates[i];
backtracking(candidates, ret, arr, visited, target, sum, i+1);
visited[i] = 0;
sum-= candidates[i];
arr.remove(arr.size()-1);
}
}
}

39. Combination Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

回溯,记录当前加和。
遍历所有数组元素,当sum大于target时返回,等于target时加入数组并返回。
每次遍历并回溯元素时只递归当前元素和其之后的元素。(防止重复。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ret = new ArrayList<>();
backtracking(candidates, ret, new ArrayList<>(), target, 0, 0);
return ret;
}

private void backtracking(int[] candidates, List<List<Integer>> ret, List<Integer> arr, int target, int sum, int level){
if(sum > target ){
return;
}
else if (sum == target){
ret.add(new ArrayList<>(arr));
return;
}

for(int i = level; i < candidates.length; i++){
arr.add(candidates[i]);
sum+= candidates[i];
backtracking(candidates, ret, arr, target, sum, i);
sum-= candidates[i];
arr.remove(arr.size()-1);
}
}
}

47. Permutations II

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

首先排序,对于有重复数据的数组,排序可以方便剪枝。
回溯,每次遍历数组内的元素。
创建一个数组记录元素是否已被遍历。
遍历时如果数组已经被记录,或者当前元素与数组中的上一个元素相等,且上一个数组未被选择,则跳过。
(如果上一个同样的数字没被选择,则放弃这个排列。即在元素相同时,优先选择前面的元素进行排列)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
Arrays.sort(nums);
int[] visited = new int[nums.length];
backtracking(ret, new ArrayList<>(), visited , nums);

return ret;
}

private void backtracking(List<List<Integer>> ret, List<Integer> arr, int[] visited, int[] nums){
if(arr.size() == nums.length){
ret.add(new LinkedList<>(arr));
return;
}

for(int i = 0; i < nums.length; i++){
if(visited[i] == 1) continue;
if(i > 0 && nums[i] == nums[i-1] && visited[i-1] == 0) continue;
arr.add(nums[i]);
visited[i] = 1;
backtracking(ret, arr, visited, nums);
visited[i] = 0;
arr.remove(arr.size()-1);
}
}
}

90. Subsets II

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

首先对数组进行排序,这样重复的元素将排列在一起。
接下来对每一个层级进行回溯。
进入每一个层级都根据上一级传递来的列表创建新列表。
然后对层级下的所有元素进行回溯。
剪枝,当遍历节点和上一个节点相等时,则跳过。
回溯,从列表中去掉最后一个元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
Arrays.sort(nums);
backtrack(ret, new LinkedList<Integer>(), nums, 0);
return ret;
}

private void backtrack(List<List<Integer>> ret, List<Integer> arr, int[] nums, int level){
ret.add(new LinkedList<>(arr));

for(int i = level; i < nums.length; i++){
if(i != level && nums[i] == nums[i-1]) continue;
arr.add(nums[i]);
backtrack(ret, arr, nums, i+1);
arr.remove(arr.size()-1);
}
}
}

78. Subsets

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

回溯,先添加一个空集,然后回溯各个单独节点。
递归时传入数组内当前数字之后的节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
ret.add(new ArrayList<>());

for(int i = 0; i < nums.length ; i++){
backtrack(ret, new ArrayList<>(), nums, i);
}
return ret;
}

private void backtrack(List<List<Integer>> ret, List<Integer> arr, int[] nums, int i){
if(i == nums.length-1){
arr.add(nums[i]);
ret.add(new ArrayList<>(arr));
return;
}

arr.add(nums[i]);
ret.add(new ArrayList<>(arr));
for(int j = i+1; j < nums.length; j++){
backtrack(ret, arr, nums, j);
arr.remove(arr.size()-1);
}
}
}

797. All Paths From Source to Target

Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

回溯。DFS搜索所有的路径。
当搜索到最后一个位置时,保存动态数组并返回。(此处需要深拷贝数组。)
回到上一层,取走动态数组的最后一个节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> ret = new LinkedList<>();
dfs(ret, new ArrayList<>(), graph, 0);
return ret;
}

private void dfs(List<List<Integer>> ret, List<Integer> arr, int[][] graph, int i){
if( i == graph.length - 1){
arr.add(i);
ret.add(new ArrayList(arr));
return;
}
arr.add(i);
for( int j : graph[i] ){
dfs(ret, arr, graph, j);
arr.remove(arr.size()-1);
}
}
}

572. Subtree of Another Tree

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node’s descendants. The tree tree could also be considered as a subtree of itself.

帮助方法isEqual,DFS搜索判断两个节点的子节点是否完全相同。
DFS搜索,如果两个根节点的值相等则返回,且调用isEqual方法,如果子节点都相同则返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
return dfs(root, subRoot) != null;
}

private TreeNode dfs(TreeNode root, TreeNode subRoot){
if(root == null) return null;
if(root.val == subRoot.val && isEqual(root, subRoot)) return root;
if(dfs(root.left, subRoot) != null ) return dfs(root.left, subRoot);
else return dfs(root.right, subRoot);
}

private boolean isEqual(TreeNode root, TreeNode subRoot){
if(root == null || subRoot == null) return root == subRoot;
if(root.val != subRoot.val) return false;
return isEqual(root.left, subRoot.left) && isEqual(root.right, subRoot.right);
}
}

547. Number of Provinces

There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

DFS搜索,当map[i][i] = 1时加入搜索。
搜索时将map[i][i]设为0。遍历并递归其数列。
当map[i][i]等于0时,返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
int[][] map;
public int findCircleNum(int[][] isConnected) {
map = isConnected;
int count = 0;

for(int i = 0; i < isConnected.length; i++){
if(map[i][i] == 1){
count++;
dfs(i);
}
}
return count;
}

private void dfs(int i){
if(map[i][i] == 0){
return;
}
map[i][i] = 0;
for(int j = 0; j < map[0].length; j++){
if(map[i][j] == 1){
dfs(j);
}
}
}
}
200. Number of Islands

200. Number of Islands

Question

Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Solution

遍历所有点,如果等于1则对其进行DFS搜索。
在搜索的同时将1设为0。
如果等于0则递归返回。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
char[][] area;
public int numIslands(char[][] grid) {
area = grid;
int count = 0;

for(int i = 0; i < area.length; i++){
for(int j = 0; j < area[0].length; j++){
if(area[i][j] == '1'){
dfs(i, j);
count++;
}
}
}
return count;
}

private void dfs(int i, int j){
if(area[i][j] == '0'){
return;
}
area[i][j] = '0';

if( i+1 < area.length ){
dfs(i+1, j);
}
if( i-1 >= 0 ){
dfs(i-1, j);
}
if( j+1 < area[0].length ){
dfs(i, j+1);
}
if( j-1 >= 0 ){
dfs(i, j-1);
}
}
}

Solution 2

同样是dfs搜索遍历每个位置,然而这个方法使用visited[][]数组来记录点是否被访问过。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
int[][] visited;
char[][] map;
int[][] operations;
public int numIslands(char[][] grid) {
visited = new int[grid.length][grid[0].length];
map = grid;
int count = 0;
operations = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(visited[i][j] == 1 || map[i][j] == '0') continue;
dfs(i, j);
count++;
}
}
return count;
}

private void dfs(int x, int y){
if(x < 0 || x >= map.length || y < 0 || y >= map[0].length ) return;
if(visited[x][y] == 1 || map[x][y] == '0') return;
visited[x][y] = 1;
for(int[] operation : operations){
int m = x + operation[0];
int n = y + operation[1];
dfs(m, n);
}

}
}

99. Recover Binary Search Tree

You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

DFS中序搜索,额外记录访问的前一个节点。
如果当前节点与前一个节点的顺序不对,则暂且认为先后两个节点的位置均不正确。
(前一个大于后一个的值,由于是第一个不满足递增条件的位置,因此前一个的位置一定是错误的。但此时当前值不一定是错误的。)
继续递归,如果发现新的节点位置不正确,则后一个节点位置正确,更新当前节点为不正确的节点。
(由于是第二个不满足递增条件的位置,因此当前值是错误的。)
交换两个位置不正确的节点的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode prev;
boolean flag;
TreeNode[] wrong;
public void recoverTree(TreeNode root) {
wrong = new TreeNode[2];
prev = new TreeNode(Integer.MIN_VALUE);
flag = true;

dfs(root);

int swap = wrong[0].val;
wrong[0].val = wrong[1].val;
wrong[1].val = swap;


}

private void dfs(TreeNode root){
if(root == null){
return;
}
dfs(root.left);
if(prev.val > root.val){
if(flag){
wrong[0] = prev;
flag = false;
}
wrong[1] = root;
}
prev = root;
dfs(root.right);
}
}

230. Kth Smallest Element in a BST

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

DFS搜索,遍历的时候更新全局变量count。
采用中序搜索,当count等于k时,将全局变量ans设置为root.val。
搜索完毕返回ans。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int ans;
int count;
public int kthSmallest(TreeNode root, int k) {
ans = -1;
count = 0;
dfs(root,k);
return ans;
}

private void dfs(TreeNode root, int k){
if(root == null){
return;
}
dfs(root.left,k);
count++;
if (k == count){
ans = root.val;
}
dfs(root.right,k);
}
}