1. class Solution {
  2. public List<List<Integer>> permute(int[] nums) {
  3. List<List<Integer>> result = new ArrayList<>();
  4. List<Integer> temp = new ArrayList<>();
  5.  
  6. // to keep track if element is included in permutation or not
  7. boolean[] visited = new boolean[nums.length];
  8. findPermutations(nums, visited, result, temp);
  9. return result;
  10. }
  11.  
  12. public void findPermutations(int[] nums, boolean[] visited, List<List<Integer>> result, List<Integer> temp)
  13. {
  14. // Base condition : when temp array becomes equal to actual size of array
  15. if(temp.size() == nums.length)
  16. {
  17. result.add(new ArrayList<>(temp));
  18. return;
  19. }
  20.  
  21. for(int i=0; i<nums.length; i++)
  22. {
  23. if(visited[i] == false)
  24. {
  25. // solve: pick the current element if it's not added in permutation
  26. temp.add(nums[i]);
  27. visited[i] = true;
  28.  
  29. // explore: calling recursively
  30. findPermutations(nums, visited, result, temp);
  31.  
  32. // backtrack: do not pick the element
  33. temp.remove(temp.size() - 1);
  34. visited[i] = false;
  35. }
  36. }
  37. return;
  38. }
  39. }