<p>The set <code>[1, 2, 3, ...,&nbsp;n]</code> contains a total of <code>n!</code> unique permutations.</p>

<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>

<ol>
	<li><code>&quot;123&quot;</code></li>
	<li><code>&quot;132&quot;</code></li>
	<li><code>&quot;213&quot;</code></li>
	<li><code>&quot;231&quot;</code></li>
	<li><code>&quot;312&quot;</code></li>
	<li><code>&quot;321&quot;</code></li>
</ol>

<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 9</code></li>
	<li><code>1 &lt;= k &lt;= n!</code></li>
</ul>

class Solution {
public:



  long factorial(int n) {  
    if (n < 0) {  
        cout << "Factorial is not defined for negative numbers." << endl;  
        return 0; // Return 0 or handle the error as needed  
    }  

      long result = 1;  
    for (int i = 1; i <= n; ++i) {  
        result *= i;  
    }  
    return result;  
}
void getPermutation2(int n, int k,set<int> &st,string &s) {
    if(n==0)return;
        long oneless = factorial(n-1);
        int val = k/oneless;
        int rem = k%oneless;
        std::set<int>::iterator itr = st.begin();
    
    // Advance the iterator to the desired position
    std::advance(itr, val);
    int num = *itr;
    char c = num+'0';
     s+=c;
        st.erase(num);
        getPermutation2(n-1,rem,st,s);
}  
        
    
    string getPermutation(int n, int k) {
        string s="";
        set<int> st;
        for(int i=0;i<n;i++){
            st.insert(i+1);
        }
        k=k-1;
        getPermutation2(n,k,st,s);
        return s; 
    }
};
7700