解法1:利用数组记录已访问过的元素

import java.util.*;
public class Solution {
    ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> permute(int[] nums) {
        if (nums == null || nums.length < 1) return res;
        Arrays.sort(nums);
        ArrayList<Integer> list = new ArrayList<Integer>();
        solve(list, nums);
        return res;
    }

    private void solve(ArrayList<Integer> list, int[] nums) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<Integer>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!list.contains(nums[i])) {   //如果已经包含就不再加入---相当于剪纸啊?
                list.add(nums[i]);
                solve(list, nums);
                list.remove(list.size() - 1);
            }
        }
    }
}

解法2:利用交换

import java.util.*;
public class Solution {
    ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();

    public ArrayList<ArrayList<Integer>> permute(int[] nums) {
        if (nums == null || nums.length < 1) return res;
        Arrays.sort(nums);
        process1(nums,0);
        return res;
    }

    public void process1(int[] chs,int i){
        if(i==chs.length){
            ArrayList<Integer>list=new ArrayList<Integer>();
            for(int a : chs){
                list.add(a);
            }
            res.add(list);
            return;
        }
        for(int j=i;j<chs.length;j++){
            swap(chs,i,j);
            process1(chs,i+1);
        }
    }

    public static void swap(int[] chs, int i, int j) {
        int tmp = chs[i];
        chs[i] = chs[j];
        chs[j] = tmp;
    }
}