ningendo

回溯法3,排列

一.题源

  https://www.lintcode.com/problem/permutations/description

   https://leetcode-cn.com/problems/permutations/

 

二.代码

 

 1 public class Solution {
 2     public static void main(String[] args) {
 3         int[] arr = new int[]{1,2,3};
 4 
 5         ArrayUtils.displayArrayList(permute(arr));
 6     }
 7 
 8     public static List<List<Integer>> permute(int[] nums) {
 9         List<List<Integer>> result = new ArrayList<>();
10 
11         boolean[] used = new boolean[nums.length];
12         backTrace(result,new ArrayList<>(),nums,used);
13 
14         return result;
15     }
16 
17     private static void backTrace(List<List<Integer>> result,List<Integer> list,int[] nums,boolean[] used){
18         if (list.size()==nums.length){
19             result.add(new ArrayList<>(list));
20             return;
21         }
22 
23         for (int i = 0; i < nums.length; i++) {
24             if(used[i]){
25                 continue;
26             }
27             list.add(nums[i]);
28             used[i] = true;
29             backTrace(result,list,nums,used);
30             list.remove(list.size()-1);
31             used[i] = false;
32         }
33     }
34 }

 

输出

[
    [1,2,3],
    [1,3,2],
    [2,1,3],
    [2,3,1],
    [3,1,2],
    [3,2,1]
]

  

 

三.图解分析

 

 

四.总结

  基本思路是,遍历列出所有的情况,包括重复的,然后设置好排除条件,如已经访问过的数字,就过滤掉,不让加入解集中去。

   关键点:就是设置好排除条件,比如上题中使用了used数组来标记访问过的元素,也可以使用别的方式。

posted on 2020-10-20 18:28  Lunamonna  阅读(57)  评论(0编辑  收藏  举报

导航