第46题

传送门

 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
class Solution {
    public static int N = 20;
    public static int [] path = new int[N];
    public static int [] flag = new int[N];
    public static List<List<Integer>> li = new ArrayList<>();
    public static void dfs(int u,int n,int [] nums){
        // li.clear();
        if(u==n){
            List<Integer> list = new ArrayList();
            for(int i=0;i<n;i++){
                list.add(path[i]);
            }
            li.add(list);
            return;
        }
        for(int i = 0;i<nums.length;i++){
            if(flag[i]==0){
                path[u] = nums[i];
                flag[i] = 1;
                dfs(u+1,n,nums);
                flag[i] = 0;
            }
        }
    }
    public List<List<Integer>> permute(int[] nums) {
        int n = nums.length;
        li.clear();
        dfs(0,n,nums);
        return li;
    }
}