image.png

回溯概念

回溯法也可以叫做回溯搜索法,它是一种搜索的方式。 回溯是递归的副产品,只要有递归就会有回溯。 所以以下讲解中,回溯函数也就是递归函数,指的都是一个函数

回溯法的效率

image.png

回溯法解决的问题

image.png

如何理解回溯法

image.png

回溯法模板

image.png
image.png
image.png

组合问题

77. 组合

给定两个整数 nk,返回范围 [1, n] 中所有可能的 k 个数的组合。你可以按 任何顺序 返回答案。

image.png

剪枝操作

image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> combine(int n, int k) {
  3. List<List<Integer>> result = new ArrayList<>();
  4. backtracking(n,k,result,1,new ArrayList<>());
  5. return result;
  6. }
  7. private void backtracking(int n,int k,List<List<Integer>> result,int begain,ArrayList<Integer> list){
  8. if(list.size() == k){
  9. result.add(new ArrayList<>(list));
  10. return;
  11. }
  12. for(int i = begain; i <= n; i++){
  13. list.add(i);
  14. backtracking(n,k,result,i+1,list);
  15. list.remove(list.size()-1);
  16. }
  17. }
  18. }

17. 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

image.png
image.png

  1. class Solution {
  2. List<String> res = new LinkedList<>();
  3. Map<Character,String> map = new HashMap<>();
  4. public List<String> letterCombinations(String digits) {
  5. if(digits.length() == 0){
  6. return res;
  7. }
  8. map.put('2',"abc");
  9. map.put('3',"def");
  10. map.put('4',"ghi");
  11. map.put('5',"jkl");
  12. map.put('6',"mno");
  13. map.put('7',"pqrs");
  14. map.put('8',"tuv");
  15. map.put('9',"wxyz");
  16. backtracking(digits,0,"");
  17. return res;
  18. }
  19. private void backtracking(String digits,int index,String path){
  20. if(index == digits.length()){
  21. res.add(path);
  22. return;
  23. }
  24. String s = map.get(digits.charAt(index));
  25. for(int i = 0; i < s.length(); i++){
  26. path = path + s.charAt(i);
  27. backtracking(digits,index + 1,path);
  28. path = path.substring(0,path.length() - 1);
  29. }
  30. }
  31. }

39. 组合总和

给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。

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

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

image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  3. List<List<Integer>> res = new ArrayList<>(); //结果集
  4. List<Integer> path = new ArrayList<>(); //路径结果集
  5. backtracking(candidates,target,res,path,0,0);
  6. return res;
  7. }
  8. private void backtracking(int[] candidates, int target,List<List<Integer>> res,List<Integer> path,int sum,int start){
  9. if(sum > target){
  10. return;
  11. }
  12. if(sum == target){
  13. res.add(new ArrayList<>(path));
  14. return;
  15. }
  16. for(int i = start;i < candidates.length;i++){
  17. sum += candidates[i];
  18. path.add(candidates[i]);
  19. backtracking(candidates,target,res,path,sum,i);
  20. sum -= candidates[i];
  21. path.remove(path.size() - 1);
  22. }
  23. }
  24. }

40. 组合总和 II

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。 注意:解集不能包含重复的组合。

image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
  3. List<List<Integer>> res = new ArrayList<>(); //结果集
  4. List<Integer> path = new ArrayList<>(); //路径集
  5. Arrays.sort(candidates); //排序
  6. backtracking(candidates,target,res,path,0);
  7. return res;
  8. }
  9. private void backtracking(int[] candidates,int target,List<List<Integer>> res,List<Integer> path,int start){
  10. if(target == 0){
  11. res.add(new ArrayList<>(path));
  12. return;
  13. }
  14. for(int i = start;i < candidates.length; i++){
  15. if(candidates[i] > target){ //剪枝,去除没必要的搜索
  16. return;
  17. }
  18. if (i > start && candidates[i] == candidates[i - 1]) {
  19. continue;
  20. }
  21. path.add(candidates[i]);
  22. backtracking(candidates,target - candidates[i],res,path,i+1);
  23. path.remove(path.size() - 1);
  24. }
  25. }
  26. }

216. 组合总和 III

找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。 说明: 所有数字都是正整数。 解集不能包含重复的组合。 输入: k = 3, n = 7 输出: [[1,2,4]]

image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> combinationSum3(int k, int n) {
  3. List<List<Integer>> result = new ArrayList<>(); //存放结果集
  4. ArrayList<Integer> list = new ArrayList<>(); //存放符合条件的结果
  5. backtracking(k,n,result,1,list);
  6. return result;
  7. }
  8. private void backtracking(int k,int n,List<List<Integer>> result, int start,ArrayList<Integer> list){
  9. //终止条件
  10. if(list.size() == k || n <= 0){
  11. if(list.size() == k && n == 0){
  12. result.add(new ArrayList<>(list));
  13. return;
  14. }
  15. }
  16. for(int i = start;i <= 9;i++){
  17. //处理节点
  18. list.add(i);
  19. //回溯
  20. backtracking(k,n-i,result,i+1,list);
  21. //剪枝
  22. list.remove(list.size() - 1);
  23. }
  24. }
  25. }

分割

131. 分割回文串

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 回文串 是正着读和反着读都一样的字符串。

image.png
image.png

  1. class Solution {
  2. public List<List<String>> partition(String s) {
  3. List<List<String>> res = new ArrayList<>();
  4. List<String> path = new ArrayList<>();
  5. backtracking(s,res,path,0);
  6. return res;
  7. }
  8. private void backtracking(String s,List<List<String>> res,List<String> path,int startIndex){
  9. if(startIndex == s.length()){
  10. res.add(new ArrayList<>(path));
  11. return;
  12. }
  13. for(int i = startIndex;i < s.length(); i++){
  14. if(isPalindrome(s,startIndex,i)){
  15. //截取字符串长度
  16. String str = s.substring(startIndex,i+1);
  17. path.add(str);
  18. backtracking(s,res,path,i+1);
  19. path.remove(path.size() - 1);
  20. }
  21. }
  22. }
  23. //判断是否是回文字符串
  24. private boolean isPalindrome(String s, int left,int right){
  25. for(int i = left,j = right;i < j;i++,j--){
  26. if(s.charAt(i) != s.charAt(j)){
  27. return false;
  28. }
  29. }
  30. return true;
  31. }
  32. }

子集

78. 子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

image.png
image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> subsets(int[] nums) {
  3. List<List<Integer>> res = new ArrayList<>();
  4. List<Integer> path = new ArrayList<>();
  5. backtracking(nums,res,path,0);
  6. return res;
  7. }
  8. private void backtracking(int[] nums,List<List<Integer>> res, List<Integer> path,int startIndex){
  9. res.add(new ArrayList<>(path)); //子集收集树形结构中所有节点的结果
  10. if(startIndex == nums.length){ //递归终止条件
  11. return;
  12. }
  13. for(int i = startIndex;i < nums.length; i++){
  14. path.add(nums[i]);
  15. backtracking(nums,res,path,i+1);
  16. path.remove(path.size() - 1);
  17. }
  18. }
  19. }

90. 子集 II

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> subsetsWithDup(int[] nums) {
  3. List<List<Integer>> res = new ArrayList<>();
  4. List<Integer> path = new ArrayList<>();
  5. Arrays.sort(nums);
  6. for(int i = 0;i< nums.length + 1; i++){
  7. backtracking(nums,i,0,res,path);
  8. }
  9. return res;
  10. }
  11. private void backtracking(int[] nums,int len,int startIndex,List<List<Integer>> res,List<Integer> path){
  12. if(path.size() == len){ //终止条件
  13. res.add(new ArrayList<>(path));
  14. return;
  15. }
  16. for(int i = startIndex; i< nums.length; i++){
  17. if(i > startIndex && nums[i] == nums[i-1]){ //判断是否重复取了
  18. continue;
  19. }
  20. path.add(nums[i]);
  21. backtracking(nums,len,i+1,res,path);
  22. path.remove(path.size() - 1);
  23. }
  24. }
  25. }

image.png

image.png

  1. class Solution {
  2. List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
  3. LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
  4. boolean[] used;
  5. public List<List<Integer>> subsetsWithDup(int[] nums) {
  6. if (nums.length == 0){
  7. result.add(path);
  8. return result;
  9. }
  10. Arrays.sort(nums);
  11. used = new boolean[nums.length];
  12. subsetsWithDupHelper(nums, 0);
  13. return result;
  14. }
  15. private void subsetsWithDupHelper(int[] nums, int startIndex){
  16. result.add(new ArrayList<>(path));
  17. if (startIndex >= nums.length){
  18. return;
  19. }
  20. for (int i = startIndex; i < nums.length; i++){
  21. if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]){
  22. continue;
  23. }
  24. path.add(nums[i]);
  25. used[i] = true;
  26. subsetsWithDupHelper(nums, i + 1);
  27. path.removeLast();
  28. used[i] = false;
  29. }
  30. }
  31. }

排列

46. 全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> permute(int[] nums) {
  3. List<List<Integer>> result = new ArrayList<>();
  4. HashMap<Integer,Boolean> visited = new HashMap<>();
  5. for(int num : nums){
  6. visited.put(num,false);
  7. }
  8. backtracking(nums,result,visited,new ArrayList<>());
  9. return result;
  10. }
  11. private void backtracking(int[] nums, List<List<Integer>> result,HashMap<Integer,Boolean> visited,ArrayList<Integer> list){
  12. if(list.size() == nums.length){
  13. result.add(new ArrayList<>(list));
  14. return;
  15. }
  16. for(int i = 0; i< nums.length; i++){
  17. int num = nums[i];
  18. if(!visited.get(num)){
  19. list.add(num);
  20. visited.put(num,true);
  21. backtracking(nums,result,visited,list);
  22. list.remove(list.size() - 1);
  23. visited.put(num,false);
  24. }
  25. }
  26. }
  27. }

47. 全排列 II

给定一个可包含重复数字的序列 nums按任意顺序 返回所有不重复的全排列。

image.png
image.png

  1. class Solution {
  2. public List<List<Integer>> result = new LinkedList<>();
  3. public List<List<Integer>> permuteUnique(int[] nums) {
  4. if(nums.length == 0){ //判空
  5. return result;
  6. }
  7. //首先给数组排序
  8. Arrays.sort(nums);
  9. findUnique(nums,new boolean[nums.length],new LinkedList<Integer>());
  10. return result;
  11. }
  12. public void findUnique(int[] nums, boolean[] visited,LinkedList<Integer> trace){
  13. //结束条件
  14. if(trace.size() == nums.length){
  15. result.add(new LinkedList(trace));
  16. return ;
  17. }
  18. //选择列表
  19. for(int i = 0; i<nums.length; i++){
  20. //其次,我们已经选择过的不需要再放进去了
  21. if(visited[i]) continue;
  22. //接下来,如果当前节点与他的前一个节点一样,并其他的前一个节点已经被遍历过了,那我们也就不需要了。
  23. if(i>0 && nums[i] == nums[i-1] && visited[i-1]) break;
  24. //做出选择
  25. trace.add(nums[i]);
  26. visited[i] = true;
  27. findUnique(nums,visited,trace);
  28. //撤销选择
  29. trace.removeLast();
  30. visited[i] = false;
  31. }
  32. }
  33. }

image.png

image.png

  1. class Solution {
  2. List<List<Integer>> result = new LinkedList<>();
  3. List<Integer> path = new ArrayList<>();
  4. public List<List<Integer>> permuteUnique(int[] nums) {
  5. boolean[] used = new boolean[nums.length];
  6. if(nums.length == 0) return result;
  7. Arrays.fill(used, false);
  8. Arrays.sort(nums);
  9. backtracking(nums, used);
  10. return result;
  11. }
  12. private void backtracking(int[] nums, boolean[] used){
  13. if(path.size() == nums.length){
  14. result.add(new ArrayList<>(path));
  15. return;
  16. }
  17. // used[i - 1] == true,说明同⼀树⽀nums[i - 1]使⽤过
  18. // 如果同⼀树层nums[i - 1]使⽤过则直接跳过
  19. // used[i - 1] == false,说明同⼀树层nums[i - 1]使⽤过
  20. for(int i = 0; i < nums.length; i++){
  21. if(i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false){
  22. continue;
  23. }
  24. if(used[i] == false){ //如果同⼀树⽀nums[i]没使⽤过开始处理
  25. used[i] = true; //标记同⼀树⽀nums[i]使⽤过,防止同一树支重复使用
  26. path.add(nums[i]);
  27. backtracking(nums, used);
  28. path.remove(path.size() - 1); //回溯,说明同⼀树层nums[i]使⽤过,防止下一树层重复
  29. used[i] = false;
  30. }
  31. }
  32. }
  33. }

491. 递增子序列

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。 示例 1:

输入:nums = [4,6,7,7] 输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] 示例 2:

输入:nums = [4,4,3,2,1] 输出:[[4,4]]

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

image.png
image.png

  1. class Solution {
  2. private List<Integer> path = new ArrayList<>();
  3. private List<List<Integer>> res = new ArrayList<>();
  4. public List<List<Integer>> findSubsequences(int[] nums) {
  5. backtracking(nums,0);
  6. return res;
  7. }
  8. private void backtracking (int[] nums, int start) {
  9. if (path.size() > 1) {
  10. res.add(new ArrayList<>(path));
  11. }
  12. int[] used = new int[201];
  13. for (int i = start; i < nums.length; i++) {
  14. if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) ||
  15. (used[nums[i] + 100] == 1)) continue;
  16. used[nums[i] + 100] = 1;
  17. path.add(nums[i]);
  18. backtracking(nums, i + 1);
  19. path.remove(path.size() - 1);
  20. }
  21. }
  22. }

剑指 Offer 12. 矩阵中的路径

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

image.png
image.png

  1. class Solution {
  2. public boolean exist(char[][] board, String word) {
  3. char[] words = word.toCharArray();
  4. for(int i = 0; i < board.length; i++){
  5. for(int j = 0; j < board[0].length; j++){
  6. if(dfs(board, words, i, j, 0)){
  7. return true;
  8. }
  9. }
  10. }
  11. return false;
  12. }
  13. public boolean dfs(char[][] board, char[] word, int i, int j, int k){
  14. if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]){
  15. return false;
  16. }
  17. if(k == word.length - 1){
  18. return true;
  19. }
  20. board[i][j] = '\0';
  21. boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
  22. dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i, j - 1, k + 1);
  23. board[i][j] = word[k];
  24. return res;
  25. }
  26. }