Math behind leetcode problem 47 permutations II Please tell me why the expression i&gt;0 &amp;&amp; nums[i] == nums[i-1] &amp;&amp; !used[i-1] works on getting unique permutations. And what is the math behind it?
The problem is as follows:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

Here is the code:
class Solution {
public:
    vector&lt;vector&lt;int&gt;&gt; permuteUnique(vector&lt;int&gt;&amp; nums) {   
        vector&lt;vector&lt;int&gt;&gt; result; 
        vector&lt;int&gt; temp;
        vector&lt;bool&gt; used(nums.size(), false);
        sort(nums.begin(), nums.end());
        backtrack(nums, temp, result, used);
        return result;        
    }
    
    void backtrack(vector&lt;int&gt;&amp; nums, vector&lt;int&gt;&amp; temp, vector&lt;vector&lt;int&gt;&gt;&amp; result, vector&lt;bool&gt;&amp; used){
        
        if(temp.size() == nums.size()){
            result.emplace_back(temp);
        }else{
            
            for(int i=0; i&lt;nums.size(); i++){
                if(used[i] || i&gt;0 &amp;&amp; nums[i] == nums[i-1] &amp;&amp; !used[i-1]) continue; 
                used[i] = true;
                temp.push_back(nums[i]);
                backtrack(nums, temp, result, used);
                used[i] = false;
                temp.pop_back();
            }            
        }        
    }    
};
(1) You are sorting the vector so duplicate values will be consecutively present in the vector.
(2) Now we come to the logic behind that condition:

As the vector can contain the duplicates we should make sure not to repeat the same sequence by starting with the same element again(duplicate)

example :

1,1,2 (starting with first one) and 1,1,2 (starting with second one) =&gt; both are same (we should make sure this doesn't happen)





Example: In [1, 1, 2]

If the first element in the sequence is chosen as 1, then we should make sure we are not going to create another sequence starting with another 1 (duplicate of the element).

So for that, we need to skip the loop for all the consecutive duplicate elements.

In your case, after creating a sequence staring with first 1, when we enter the loop for the second time we check whether the current element is a duplicate nums[i] == nums[i - 1] (this is sufficient as you have already sorted the vector) and whether the current element is the first element of the sequence !used[i - 1].

In your case, due to this condition, the second one cannot be the first element of the sequence.