数组的全排列

要求:给出数组A={a_0,a_1,a_2,...,a_n}(n是可变的),打印出所有元素的组合

leetcode上面也有这道题https://leetcode.com/problems/permutations/

思路:

使用回溯BS算法,用一个visited数组保存已经访问过的元素,使用一个list保存已经生成一个排列。

开始没有使用list保存前面的记录,显示的时候就会显示后面一部分,不会显示前面部分

--------------------------------------------------我是代码分割线-------------------------------------------------------

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 /**
 5  * 数组的全排列
 6  * 回溯算法的应用
 7  * 需要对前面的状态进行记录,所以用了一个list记录
 8  * @author GXF
 9  *
10  */
11 public class Permutations {
12     private boolean visited[] = new boolean[6];    
13     
14     public void dfs(int nums[], int depth, List<Integer> cur){
15         if(nums == null)
16             return;
17         if(depth == nums.length)
18         {            
19             System.out.println(cur);
20             return;
21         }
22         for(int i = 0; i < nums.length; i++){
23             if(visited[i] == false){
24                 visited[i] = true;
25                 cur.add(nums[i]);
26                 dfs(nums, depth + 1, cur);
27                 cur.remove(cur.size() - 1);
28                 visited[i] = false;
29             }
30         }
31     }
32     
33     public static void main(String args[]){
34         Permutations permutations = new Permutations();
35         List<Integer> cur = new ArrayList<Integer>();
36         int nums[] = {1,2,3,4,5,6};
37         permutations.dfs(nums, 0, cur);
38     }
39 }
原文地址:https://www.cnblogs.com/luckygxf/p/4693284.html