title: What is the purpose of "undoing" steps after a recursive call (JAVA)?
body: <p>This is a snippet to create all possible permutations of an integer array. I would specifically like to know the purpose of the line when the last element is removed from the tempList. I have tried to add print statements everywhere, but I am still not conceptually understanding the recursive backtracking that takes place.</p>
  
  <pre><code>public List&lt;List&lt;Integer&gt;&gt; permute(int[] nums) {
     List&lt;List&lt;Integer&gt;&gt; list = new ArrayList&lt;&gt;();
     // Arrays.sort(nums); // not necessary
     backtrack(list, new ArrayList&lt;&gt;(), nums);
     return list;
  }
  
  private void backtrack(List&lt;List&lt;Integer&gt;&gt; list, List&lt;Integer&gt; tempList, int [] nums){
     if(tempList.size() == nums.length){
        list.add(new ArrayList&lt;&gt;(tempList));
     } else{
        for(int i = 0; i &lt; nums.length; i++){ 
           if(tempList.contains(nums[i])) continue; // element already exists, skip
           tempList.add(nums[i]);
           backtrack(list, tempList, nums);
           tempList.remove(tempList.size() - 1);
        }
     }
  } 
  </code></pre>