• LeetCode —— 回溯


    77. 组合

    给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

    示例:输入:n = 4, k = 2         输出: [ [1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> combine(int n, int k) {
    5. backTrack(n, k, 1);
    6. return list;
    7. }
    8. public void backTrack(int n, int k, int startIndex){
    9. if(path.size() == k){
    10. list.add(new ArrayList<>(path));
    11. return;
    12. }
    13. for(int i = startIndex; i <= n; i++){
    14. path.add(i);
    15. backTrack(n, k, i + 1);
    16. path.removeLast();
    17. }
    18. }
    19. }

    216. 组合总和III

    找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:(1)只使用数字1到9;(2)每个数字 最多使用一次 。返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

    示例:输入: k = 3, n = 9         输出: [[1,2,6], [1,3,5], [2,3,4]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> combinationSum3(int k, int n) {
    5. backTrack(k, n, 1, 0);
    6. return list;
    7. }
    8. public void backTrack(int k, int targetSum, int startIndex, int sum){
    9. if(sum > targetSum || path.size() > k){
    10. return;
    11. }
    12. if(path.size() == k && sum == targetSum){
    13. list.add(new ArrayList<>(path));
    14. return;
    15. }
    16. for(int i = startIndex; i <= 9; i++){
    17. path.add(i);
    18. sum += i;
    19. backTrack(k, targetSum, i + 1, sum);
    20. path.removeLast();
    21. sum -= i;
    22. }
    23. }
    24. }

    39.  组合总和

    给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

    示例:输入:candidates = [2,3,6,7], target = 7         输出:[[2,2,3],[7]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> combinationSum(int[] candidates, int target) {
    5. Arrays.sort(candidates);
    6. backTrack(candidates, target, 0, 0);
    7. return list;
    8. }
    9. public void backTrack(int[] candidates, int target, int index, int sum){
    10. if(sum > target){
    11. return;
    12. }
    13. if(sum == target){
    14. list.add(new ArrayList<>(path));
    15. return;
    16. }
    17. for(int i = index; i < candidates.length; i++){
    18. path.add(candidates[i]);
    19. sum += candidates[i];
    20. backTrack(candidates, target, i, sum);
    21. sum -= candidates[i];
    22. path.removeLast();
    23. }
    24. }
    25. }

    40. 组合总和II

    给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的每个数字在每个组合中只能使用 一次 。

    示例:输入: candidates = [10,1,2,7,6,1,5], target = 8       输出: [ [1,1,6], [1,2,5], [1,7], [2,6] ]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> combinationSum2(int[] candidates, int target) {
    5. Arrays.sort(candidates);
    6. backTrack(candidates, target, 0, 0);
    7. return list;
    8. }
    9. public void backTrack(int[] candidates, int target, int startIndex, int sum){
    10. if(sum == target){
    11. list.add(new ArrayList<>(path));
    12. return;
    13. }
    14. for(int i = startIndex; i < candidates.length; i++){
    15. if(sum + candidates[i] > target){
    16. break;
    17. }
    18. // 跳过同一层使用过的元素(必须在数组有序时才可以这样使用)
    19. if(i > startIndex && candidates[i] == candidates[i - 1]){
    20. continue;
    21. }
    22. path.add(candidates[i]);
    23. sum += candidates[i];
    24. backTrack(candidates, target, i + 1, sum);
    25. sum -= candidates[i];
    26. path.removeLast();
    27. }
    28. }
    29. }
    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> combinationSum2(int[] candidates, int target) {
    5. Arrays.sort(candidates);
    6. back(candidates, target, 0, 0);
    7. return list;
    8. }
    9. public void back(int[] candidates, int target, int startIndex, int sum){
    10. if(sum > target){
    11. return;
    12. }
    13. if(sum == target){
    14. list.add(new ArrayList<>(path));
    15. return;
    16. }
    17. Set set = new HashSet<>();
    18. for(int i = startIndex; i < candidates.length; i++){
    19. if(set.contains(candidates[i])){
    20. continue;
    21. }
    22. set.add(candidates[i]);
    23. path.add(candidates[i]);
    24. sum += candidates[i];
    25. back(candidates, target, i + 1, sum);
    26. sum -= candidates[i];
    27. path.removeLast();
    28. }
    29. }
    30. }

    17. 电话号码的字母组合

    给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

    给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

    示例:输入:digits = "23"         输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

    1. class Solution {
    2. List list = new ArrayList<>();
    3. StringBuilder item = new StringBuilder();
    4. public List letterCombinations(String digits) {
    5. if(digits.length() == 0){
    6. return list;
    7. }
    8. String[] numberString = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    9. backTrack(digits, numberString, 0);
    10. return list;
    11. }
    12. public void backTrack(String digits, String[] numberString, int index){
    13. if(item.length() == digits.length()){
    14. list.add(item.toString());
    15. return;
    16. }
    17. String cur = numberString[digits.charAt(index) - '0'];
    18. for(int i = 0; i < cur.length(); i++){
    19. item.append(cur.charAt(i));
    20. backTrack(digits, numberString, index + 1);
    21. item.deleteCharAt(item.length() - 1);
    22. }
    23. }
    24. }

     131. 分割回文子串

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

    示例:输入:s = "aab"         输出:[["a","a","b"],["aa","b"]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList item = new LinkedList<>();
    4. public List> partition(String s) {
    5. backTrack(s, 0);
    6. return list;
    7. }
    8. public void backTrack(String s, int startIndex){
    9. if(startIndex >= s.length()){
    10. list.add(new ArrayList<>(item));
    11. return;
    12. }
    13. for(int i = startIndex; i < s.length(); i++){
    14. if(!isPalindrome(s, startIndex, i)){
    15. continue;
    16. }
    17. item.add(s.substring(startIndex, i + 1));
    18. backTrack(s, i + 1);
    19. item.removeLast();
    20. }
    21. }
    22. public boolean isPalindrome(String s, int left, int right){
    23. while(left <= right){
    24. if(s.charAt(left) != s.charAt(right)){
    25. return false;
    26. }
    27. left++;
    28. right--;
    29. }
    30. return true;
    31. }
    32. }

    78. 子集

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

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

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> subsets(int[] nums) {
    5. backTrack(nums, 0);
    6. return list;
    7. }
    8. public void backTrack(int[] nums, int startIndex){
    9. list.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. backTrack(nums, i + 1);
    16. path.removeLast();
    17. }
    18. }
    19. }

    90. 子集II

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

    示例:输入:nums = [1,2,2]         输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> subsetsWithDup(int[] nums) {
    5. Arrays.sort(nums);
    6. backTrack(nums, 0);
    7. return list;
    8. }
    9. public void backTrack(int[] nums, int startIndex){
    10. list.add(new ArrayList<>(path));
    11. if(startIndex >= nums.length){ // 可以省略
    12. return;
    13. }
    14. for(int i = startIndex; i < nums.length; i++){
    15. if(i > startIndex && nums[i] == nums[i - 1]){
    16. continue;
    17. }
    18. path.add(nums[i]);
    19. backTrack(nums, i + 1);
    20. path.removeLast();
    21. }
    22. }
    23. }
    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> subsetsWithDup(int[] nums) {
    5. Arrays.sort(nums);
    6. backTrack(nums, 0);
    7. return list;
    8. }
    9. public void backTrack(int[] nums, int startIndex){
    10. list.add(new ArrayList<>(path));
    11. if(startIndex >= nums.length){
    12. return;
    13. }
    14. Set set = new HashSet<>();
    15. for(int i = startIndex; i < nums.length; i++){
    16. if(set.contains(nums[i])){
    17. continue;
    18. }
    19. set.add(nums[i]);
    20. path.add(nums[i]);
    21. backTrack(nums, i + 1);
    22. path.removeLast();
    23. }
    24. }
    25. }

    491. 递增子序列

    给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

    示例:输入: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]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> findSubsequences(int[] nums) {
    5. backTrack(nums, 0);
    6. return list;
    7. }
    8. public void backTrack(int[] nums, int startIndex){
    9. if(path.size() >= 2){
    10. list.add(new ArrayList<>(path));
    11. }
    12. // 由于数组无序,因此不能使用 if(i > startIndex && nums[i] == nums[i - 1])
    13. HashSet set = new HashSet<>();
    14. for(int i = startIndex; i < nums.length; i++){
    15. if((!path.isEmpty() && nums[i] < path.getLast()) || set.contains(nums[i])){
    16. continue;
    17. }
    18. set.add(nums[i]);
    19. path.add(nums[i]);
    20. backTrack(nums, i + 1);
    21. path.removeLast();
    22. }
    23. }
    24. }

    46. 全排列

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

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

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> permute(int[] nums) {
    5. boolean[] used = new boolean[nums.length];
    6. backTrack(nums, used);
    7. return list;
    8. }
    9. public void backTrack(int[] nums, boolean[] used){
    10. if(path.size() == nums.length){
    11. list.add(new ArrayList<>(path));
    12. return;
    13. }
    14. for(int i = 0; i < nums.length; i++){
    15. if(used[i]){
    16. continue;
    17. }
    18. used[i] = true;
    19. path.add(nums[i]);
    20. backTrack(nums, used);
    21. path.removeLast();
    22. used[i] = false;
    23. }
    24. }
    25. }

    47. 全排列II

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

    示例:输入:nums = [1,1,2]         输出: [[1,1,2], [1,2,1], [2,1,1]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> permuteUnique(int[] nums) {
    5. Arrays.sort(nums);
    6. boolean[] used = new boolean[nums.length];
    7. backTrack(nums, used);
    8. return list;
    9. }
    10. public void backTrack(int[] nums, boolean[] used){
    11. if(path.size() == nums.length){
    12. list.add(new ArrayList<>(path));
    13. return;
    14. }
    15. for(int i = 0; i < nums.length; i++){
    16. if(used[i] == true || (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false)){
    17. continue;
    18. }
    19. used[i] = true;
    20. path.add(nums[i]);
    21. backTrack(nums, used);
    22. path.removeLast();
    23. used[i] = false;
    24. }
    25. }
    26. }
    1. class Solution {
    2. List> list = new ArrayList<>();
    3. LinkedList path = new LinkedList<>();
    4. public List> permuteUnique(int[] nums) {
    5. boolean[] used = new boolean[nums.length];
    6. backTrack(nums, used);
    7. return list;
    8. }
    9. public void backTrack(int[] nums, boolean[] used){
    10. if(path.size() == nums.length){
    11. list.add(new ArrayList<>(path));
    12. return;
    13. }
    14. Set set = new HashSet<>();
    15. for(int i = 0; i < nums.length; i++){
    16. if(set.contains(nums[i]) || used[i] == true){
    17. continue;
    18. }
    19. set.add(nums[i]);
    20. used[i] = true;
    21. path.add(nums[i]);
    22. backTrack(nums, used);
    23. used[i] = false;
    24. path.removeLast();
    25. }
    26. }
    27. }

    93. 复原IP地址

    有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245""192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。

    给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

    示例:输入:s = "25525511135"         输出:["255.255.11.135","255.255.111.35"]

    1. class Solution {
    2. List list = new ArrayList<>();
    3. public List restoreIpAddresses(String s) {
    4. if(s.length() > 12){
    5. return list;
    6. }
    7. backTrack(s, 0, 0);
    8. return list;
    9. }
    10. public void backTrack(String s, int startIndex, int pointNum){
    11. if(pointNum == 3){ // 分割数量为3时,分隔结束
    12. if(isValid(s, startIndex, s.length() - 1)){ // 判断第四段⼦字符串是否合法
    13. list.add(s);
    14. }
    15. return;
    16. }
    17. for(int i = startIndex; i < s.length(); i++){
    18. if(!isValid(s, startIndex, i)){
    19. continue;
    20. }
    21. s = s.substring(0, i + 1) + "." + s.substring(i + 1); //在str的后⾯插⼊⼀个点
    22. pointNum++;
    23. backTrack(s, i + 2, pointNum); // 插⼊点之后下⼀个⼦串的起始位置为i+2
    24. pointNum--; // 回溯
    25. s = s.substring(0, i + 1) + s.substring(i + 2); // 回溯删掉逗点
    26. }
    27. }
    28. public Boolean isValid(String s, int left, int right) {
    29. if (left > right) {
    30. return false;
    31. }
    32. if (s.charAt(left) == '0' && left != right) { // 0开头的数字不合法
    33. return false;
    34. }
    35. int num = 0;
    36. for (int i = left; i <= right; i++) {
    37. num = num * 10 + (s.charAt(i) - '0');
    38. if (num > 255) { // 如果⼤于255了不合法
    39. return false;
    40. }
    41. }
    42. return true;
    43. }
    44. }

    51. N皇后

    按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

    示例:输入:n = 4         输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]

    1. class Solution {
    2. List> list = new ArrayList<>();
    3. public List> solveNQueens(int n) {
    4. char[][] matrix = new char[n][n];
    5. for(char[] array : matrix){
    6. Arrays.fill(array, '.');
    7. }
    8. backTrack(n, 0, matrix);
    9. return list;
    10. }
    11. public void backTrack(int n, int row, char[][] matrix){
    12. if(row == n){
    13. List item = new ArrayList<>();
    14. for(char[] array : matrix){
    15. item.add(String.valueOf(array));
    16. }
    17. list.add(item);
    18. return;
    19. }
    20. for(int column = 0; column < n; column++){
    21. if(isValid(row, column, n, matrix)){
    22. matrix[row][column] = 'Q';
    23. backTrack(n, row + 1, matrix);
    24. matrix[row][column] = '.';
    25. }
    26. }
    27. }
    28. public boolean isValid(int row, int column, int n, char[][] matrix) {
    29. // 检查列
    30. for(int i = 0; i < row; i++){
    31. if(matrix[i][column] == 'Q'){
    32. return false;
    33. }
    34. }
    35. // 检查45度对角线
    36. for(int i = row - 1, j = column - 1; i >= 0 && j >= 0; i--, j--) {
    37. if(matrix[i][j] == 'Q'){
    38. return false;
    39. }
    40. }
    41. // 检查135度对角线
    42. for(int i = row - 1, j = column + 1; i >= 0 && j <= n-1; i--, j++){
    43. if(matrix[i][j] == 'Q'){
    44. return false;
    45. }
    46. }
    47. return true;
    48. }
    49. }
  • 相关阅读:
    股票交易接口list接口索引的方法
    CleanMyMac4.11.3macOS系统垃圾清理应用
    论文研读:ViT-V-Net—用于无监督3D医学图像配准的Vision Transformer
    一种用于Linux内核驱动开发的Vim环境配置
    记一次 ClickHouse 性能测试
    Java--web.xml加载过程;文件标签详解
    “次世代”究竟是什么?次世代角色建模又该怎么学?
    使用 Temporal Fusion Transformer 进行时间序列预测
    SQL练习:表妹不在,没人帮我查表,只好自己来了
    WebGL开发数据可视化应用
  • 原文地址:https://blog.csdn.net/Archer__13/article/details/133391922