原題不長這樣,但我想求一下全排列。輸入輸出示例如下:
主要採用回溯法,第一次使用,見註釋吧。勉強能看明白,說不出來,方法太巧了。
import java.util.*;
public class Test {
public static void main(String[] args) {
int[] nums = {1,2,3};
List<List<Integer>> myres = permute(nums);
System.out.println(myres);
}
public static List<List<Integer>> res = new LinkedList<>();
/* 主函數,輸入一組不重複的數字,返回它們的全排列 */
public static List<List<Integer>> permute(int[] nums) {
// 記錄「路徑」
LinkedList<Integer> track = new LinkedList<>();
backtrack(nums, track);
return res;
}
// 路徑:記錄在 track 中
// 選擇列表:nums 中不存在於 track 的那些元素
// 結束條件:nums 中的元素全都在 track 中出現
static void backtrack(int[] nums, LinkedList<Integer> track) {
// 觸發結束條件
if (track.size() == nums.length) {
res.add(new LinkedList(track));
return;
}
for (int i = 0; i < nums.length; i++) {
// 排除不合法的選擇
if (track.contains(nums[i]))
continue;
// 做選擇
track.add(nums[i]);
// 進入下一層決策樹
backtrack(nums, track);
// 取消選擇
track.removeLast();
}
}
}