全排列-回溯解法

回溯个人感觉和dfs加visited数组差不多,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Main{
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> permute(int[] nums){
LinkedList<Integer> track = new LinkedList<>();
backTrack(track, nums);
return res;
}
public void backTrack(LinkedList<Integer> track, int[] nums){
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(track, nums);
track.removeLast();
}
}
public static void main(String[] args) {
Main m = new Main();
m.test();


}

public void test(){
permute(new int[]{1,2,3,4,5});
for(List<Integer> list : res){
for(Integer v : list){
System.out.print(v+" ");
}
System.out.println();
}
}
}
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!

扫一扫,分享到微信

微信分享二维码
  • © 2020 Zhang-Ke
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信