算法-深度优先搜索
一、深度优先搜索
DFS(Depth-First-Search)深度优先:对每一个可能的分支路径深入到不能再深入为止,而且每个结点只能访问一次。要特别注意的是,二叉树的深度优先遍历比较特殊,可以细分为先序遍历、中序遍历、后序遍历。(它的目的是要达到被搜索结构的叶结点 )
BFS: 广度优先又叫层次遍历,从上往下对每一层依次访问,在每一层中,从左往右(也可以从右往左)访问结点,访问完一层就进入下一层,直到没有结点可以访问为止。
深度优先搜索和宽度优先搜索区别
- 二叉树的深度优先遍历的非递归的通用做法是采用栈,广度优先遍历的非递归的通用做法是采用队列。
- 深度优先搜素算法:不全部保留结点,占用空间少;有回溯操作(即有入栈、出栈操作),运行速度慢。
- 广度优先搜索算法:保留全部结点,占用空间大; 无回溯操作(即无入栈、出栈操作),运行速度快。
二、排列组合
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null) {
return result;
}
if (nums.length == 0) {
result.add(new ArrayList<Integer>());
return result;
}
List<Integer> list = new ArrayList<>();
helper(result, nums, list);
return result;
}
//递归-深度优先搜索---退出条件
public void helper(List<List<Integer>> result, int[] nums, List<Integer> list) {
if (list.size() == nums.length) {
result.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (list.contains(nums[i])) {
continue;
}
list.add(nums[i]);
helper(result, nums, list);
list.remove(list.size() - 1);
}
}
}
三、字符串子集
public class Solution {
/**
* @param nums: A set of numbers
* @return: A list of lists
*/
public List<List<Integer>> subsets(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
result.add(new ArrayList<>());
return result;
}
List<Integer> list = new ArrayList<>();
Arrays.sort(nums);
dfs(nums, result, list, 0);
return result;
}
//递归-深度优先搜索---退出条件
public void dfs(int[] nums, List<List<Integer>> result, List<Integer> list, int pos) {
/*
[]
1
1, 2
1, 2, 3
1, 3
2
2, 3
3
*/
result.add(new ArrayList<Integer>(list));
for (int i = pos; i < nums.length; i++) {
list.add(nums[i]);
dfs(nums, result, list, i + 1);
//不全部保留结点
list.remove(list.size() - 1);
}
}
}