My idea is very simple. For example, if the num={1, 2, 3, 4, 5}.

First, generate a list containing just "1"; then, insert "2" before and after "1", we get "1, 2" and "2, 1"; then, for list "1, 2", we insert "3", and we get "3, 1, 2", "1, 3, 2", and "1, 2, 3"; for list "2, 1", we insert "3" again, and so forth...

Below is my code, where did I go wrong? Thanks in advance!

```
public class Solution {
public List<List<Integer>> permute(int[] num) {
return function(num, num.length);
}
//Recursive function
public static List<List<Integer>> function(int[] num, int length) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
//If length is 1, we just add the number into the list
if (length==1) {
List<Integer> temp = new ArrayList<Integer>();
temp.add(num[0]);
result.add(temp);
return result;
}
//Use for loop to traverse all lists of last iteration
//Then for every list, add the new number at every index (from 0 to list.size())
for (List<Integer> list: function(num, length-1)) {
for (int i=0; i<=list.size(); i++) {
list.add(i, num[length-1]);
result.add(list);
list.remove(i); //Remove the added number and reset the list
}
}
return result;
}
}
```