java - 如何理解leetcode中的递归?

标签 java algorithm recursion

java新手,我在leecode中阅读了答案,它要求一个像[1,2,3]这样的数组并返回其排列[1,3,2],[2,1,3].. ...并且感到困惑,尤其是这段代码

Collections.swap(output, first, i);
backtrack(n, output, res, first + 1);

我不知道为什么使用 Collections.swap(output,first,i) 我认为在第一个循环中,first 和 i 等于 0,所以为什么在这里使用 swap 。它们是相同的值。这个递归实际上做了什么,我调试它但无法弄清楚。代码如下:

package com.company;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

 class Main {

public static void main(String[] args) {
    int[]arr=new int[]{1,2,3};
    Main main1=new Main();
    List<List<Integer>> lists = main1.permute(arr);
    System.out.println(lists);

}

   public List<List<Integer>> permute(int[] nums) {
       List<List<Integer>> res = new ArrayList<List<Integer>>();

       List<Integer> output = new ArrayList<Integer>();
       for (int num : nums) {
           output.add(num);
       }

       int n = nums.length;
       backtrack(n, output, res, 0);
       return res;
   }

   public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
       
       if (first == n) {
           res.add(new ArrayList<Integer>(output));
       }
       for (int i = first; i < n; i++) {
           
           Collections.swap(output, first, i);
          
           backtrack(n, output, res, first + 1);
          
           Collections.swap(output, first, i);
       }
   }
}

最佳答案

根据documentation ,java.util.Collections类的swap()方法用于交换指定列表中指定位置的元素。 如果指定的位置相等,则调用此方法会使列表保持不变。

因此,在递归技术中,即使它在特定条件下不执行任何操作,也可以进行该调用,只是为了使逻辑更易于实现和理解。如果你想避免这种情况,你将不必要地将条件语句带入逻辑中,这实际上是不需要的。

关于java - 如何理解leetcode中的递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69187625/

相关文章:

java - JMH 静态最终字段作为参数

javascript - 计算 "Memory Game' s"分数,根据尝试次数、花费时间和剩余牌数

Python 递归与 for 循环

java - 如何检测文件中的新行(或空行)?

java - 如何在 Spring Boot 执行器中禁止 TRACE http 方法

python - 我需要在此数独 python 代码中进行解释

java - 递归查找树的高度/最深节点

java - 回文程序,无法终止循环,欧拉计划 #4

bash - 递归调用函数时如何阻止bash创建子shell

java - 使用扫描仪输入时如何写出表格?