Advertisement
exmkg

Untitled

Aug 23rd, 2024
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. class Solution {
  2.     public List<List<Integer>> permute(int[] nums) {
  3.         List<List<Integer>> list = new ArrayList<>();
  4.         backtrack(list, new ArrayList<>(), nums);
  5.         return list;
  6.     }
  7.  
  8.     // nums = [1, 2, 3]
  9.  
  10.     // Layer #0 (tempList):            
  11.     // Layer #0 (iterator i):                  
  12.  
  13.     // Layer #1 (tempList):                  
  14.     // Layer #1 (iterator i):                    
  15.  
  16.     // Layer #2 (tempList):              
  17.     // Layer #2 (iterator i):        
  18.  
  19.     // Layer #3 (tempList):   [2, 3, 1]
  20.     // Layer #3 (list): [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
  21.  
  22.     private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
  23.         if (tempList.size() == nums.length) {
  24.             list.add(new ArrayList<>(tempList));
  25.             return;
  26.         }
  27.         for (int i = 0; i < nums.length; i++) {
  28.             if (tempList.contains(nums[i])) {
  29.                 continue; // element already exists, skip
  30.             }
  31.             tempList.add(nums[i]);
  32.             backtrack(list, tempList, nums);
  33.             tempList.remove(tempList.size() - 1);
  34.         }
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement