回溯算法解全排列
package com.company;
import static java.lang.System.out;
import java.util.*;
public class Main {
static List<List<Integer>> permute(int[] nums, List<List<Integer>> trackList){
LinkedList<Integer> track = new LinkedList<>();
backtrack(nums, track, trackList);
return trackList;
}
static void backtrack(int[] nums, LinkedList<Integer> track, List<List<Integer>> trackList){
if (track.size() == nums.length){
trackList.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, trackList);
track.removeLast();
}
}
public static void main(String[] args) {
List<List<Integer>> res = new LinkedList<>();
int[] nums = {1, 2, 3};
res = permute(nums, res);
for (List<Integer> track: res){
out.println(track);
}
}
}
如果你认为对你有用,关注我的微信公众号支持我一下吧!~