Simple Java Solution 2


#1
public class Solution {
    public static ArrayList<int[]> ansList = new ArrayList<>();
    public int[][] permute(int[] A) {
        permute(A,0);
        int[][] ansArr = new int[ansList.size()][A.length];
        
        for (int i = 0 ; i < ansList.size() ; i++ ) 
            ansArr[i] = ansList.get(i);
        
        ansList.clear();
        return ansArr;
    }
    
    public static void permute(int[] intArray, int start) {
        Set<Integer> set = new HashSet<>(); // set checks for repeats
        for (int i = start; i < intArray.length; i++) {
            if (!set.contains(intArray[i])) { // checks repeat array values
                swap(intArray, i, start);
                permute(intArray, start + 1);
                swap(intArray, i, start);
            }
            set.add(intArray[i]); // add repeat to the set
        }
        if (start == intArray.length - 1) {
            ansList.add(intArray.clone());
        }
    }
    
    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}