第一次接觸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)。
}
}
uj5u.com熱心網友回復:
根據檔案,java.util.Collections類的swap()方法是用來交換指定串列中指定位置的元素的。如果指定的位置相等,呼叫該方法將使串列保持不變。
所以在一個遞回技術中,即使在那個特定的條件下不做任何事情,有這樣的呼叫也是可以的,只是為了使邏輯更容易實作和理解。如果你想避免這種情況,你將不必要地需要將條件陳述句帶入邏輯中,這其實是不需要的。
uj5u.com熱心網友回復:
下面是一個有點簡化和注釋的版本,可能有助于了解代碼的作用:
import java.util.*;
public class Main {
public static void main(String[] args){
int[]arr=new int[]{1, 2,3}。
List<List<Integer>> permutations = new Main().permute(arr)。
System.out.println(permutations)。
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>()。
List<Integer> input = new ArrayList<> ()。
for (int num : nums) {
input.add(num)。
}
backtrack(input, result, 0) 。
return result。
}
public void backtrack(List< Integer> input, List<List<Integer>> result, int currentIndex) {
if ( currentIndex == input.size() ) { //index passed the end of the collection[/span]。
result.add(new ArrayList<>(input)); //將排列組合添加到回傳結果中。
//該方法在此回傳,因為當currentIndex == input.size()時。
//下一個for回圈將不會被執行。
//你可以在這里添加一個回傳。它可以提高代碼的可讀性。
}
//對陣列中的每個元素進行迭代,從currentIndex到最后。
for (int i = currentIndex; i < input.size(); i ) {
Collections.swap(input, currentIndex, i);//通過互換創建一個包絡。
backtrack(input, result, currentIndex 1); //增加 currentIndex 并處理新的排列組合。
Collections.swap(input, currentIndex, i);//undo permutation before next loop。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/308811.html
標籤:
