Permutations
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
,
and [3,2,1]
.
public static List<List<Integer>> permute(int[] num) {
LinkedList ans = new LinkedList<>(); // queue
ans.offer(new LinkedList<Integer>()); // init with empty list
// loop through sizes of lists used for inserting new element in asc
// order
for (int n = 0; n < num.length; n++) {
// loop through all lists of a current size
while (n == ((List<List<Integer>>) ans.peek()).size()) {
List<Integer> l = (List<Integer>) ans.poll(); // next "base"
// list of a
// curr size
// loop through all position in a "base" list generating new
// list
for (int i = 0; i <= l.size(); i++) {
LinkedList<Integer> newL = new LinkedList<>(l.subList(0, i));
newL.add(num[n]);
newL.addAll(l.subList(i, l.size()));
ans.offer(newL);
}
}
}
return ans;
}
public static void main(String[] arqs) {
int[] num = new int[] { 1, 2, 3 };
List<List<Integer>> result = permute(num);
Iterator ite = result.iterator();
while (ite.hasNext()) {
List<Integer> list = (List<Integer>) ite.next();
Iterator ite_2 = list.iterator();
System.out.print("{");
while (ite_2.hasNext()) {
int x = (Integer) ite_2.next();
System.out.print(x);
}
System.out.print("}\n");
}
}