package leetcode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * https://leetcode.com/problems/permutations/
 */
public class Problem46 {
    public List<List<Integer>> permute(int[] num) {
        List<List<Integer>> result = new ArrayList<>();
        permute(result, new ArrayList<>(), new HashSet<>(), 0, num);
        return result;
    }

    private void permute(List<List<Integer>> result, List<Integer> accu,
                         Set<Integer> indices, int n, int[] num) {
        if (n == num.length) {
            result.add(accu);
            return;
        }
        for (int i = 0; i < num.length; i++) {
            if (indices.contains(i)) {
                continue;
            }
            List<Integer> newAccu = new ArrayList<>();
            for (int a : accu) {
                newAccu.add(a);
            }
            newAccu.add(num[i]);
            Set<Integer> newIndices = new HashSet<>();
            for (int idx : indices) {
                newIndices.add(idx);
            }
            newIndices.add(i);
            permute(result, newAccu, newIndices, n + 1, num);
        }
    }
}

@@ -272,22 +272,22 @@
 teger%3E%3E 
-result
+answer
  = new A
@@ -320,28 +320,35 @@
 ute(
-result, new ArrayLis
+num, num.length, new HashSe
 t%3C%3E(
@@ -358,27 +358,29 @@
 new 
-HashSe
+ArrayLis
 t%3C%3E(), 
-0, num
+answer
 );%0A 
@@ -393,22 +393,22 @@
  return 
-result
+answer
 ;%0A    %7D%0A
@@ -420,16 +420,23 @@
 private 
+static 
 void per
@@ -444,34 +444,49 @@
 ute(
-List%3CList%3CInteger%3E%3E result
+int%5B%5D num, int n, Set%3CInteger%3E duplicates
 , Li
@@ -532,46 +532,41 @@
     
-Set%3CInteger%3E indices, int n, int%5B%5D num
+       List%3CList%3CInteger%3E%3E answer
 ) %7B%0A
@@ -582,26 +582,17 @@
 f (n == 
-num.length
+0
 ) %7B%0A    
@@ -603,24 +603,41 @@
     
-result.add
+answer.add(new ArrayList%3C%3E
 (accu)
+)
 ;%0A  
@@ -727,21 +727,24 @@
     if (
-indic
+duplicat
 es.conta
@@ -809,113 +809,24 @@
     
-List%3CInteger%3E newAccu = new ArrayList%3C%3E();%0A            for (int a : accu) %7B%0A                newAccu
+duplicates
 .add(
-a
+i
 );%0A 
@@ -840,26 +840,9 @@
     
-%7D%0A            newA
+a
 ccu.
@@ -870,230 +870,128 @@
     
-Set%3CInteger%3E newIndices = new HashSet%3C%3E();%0A            for (int idx : indices) %7B%0A                newIndices.add(idx);%0A            %7D%0A            newIndices.add(i);%0A            permute(result, newAccu, newIndices, n + 1, num
+permute(num, n - 1, duplicates, accu, answer);%0A            accu.remove(accu.size() - 1);%0A            duplicates.remove(i
 );%0A 

Update problem 46