I wrote the following code for generating the permutations of given integers
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0){
return result;
}
boolean[] visited = new boolean[nums.length];
List current = new ArrayList<Integer>();
permute_recursive(visited, nums, current, result);
return result;
}
public void permute_recursive(boolean[] visited, int[] nums, List<Integer> current,
List<List<Integer>> result){
if(current.size() == nums.length){
result.add(new ArrayList<Integer>(current));
return;
}
for(int i = 0; i < nums.length; i++){
if(visited[i]){
continue;
}
visited[i] = true;
current.add(nums[i]);
permute_recursive(visited, nums, current, result);
visited[i] = false;
//do not want the next round to start with nums[i], but we just added it, so we need to
remove it.
current.remove(current.size() - 1);
}
}
}
The problem is when I do result.add(current) directly it will only return to me an empty list of arrays and I do not know why.
As requested, my main method is
public class test {
public static void main(String[] args) {
int[] test = new int[]{1,2,3};
System.out.print(Solution.permute(test));
}
}
How is this relevant though?