<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:
    def getPermutation(self, n: int, k: int) -> str:
        if n == 1:
            return "1"
        
        self.n_1_fact = 1
        for i in range(1, n):
            self.n_1_fact *= i
        self.visited = 0
        self.res = ""

        def genPerms(lst: List[int]) -> List[List[int]]:
            if len(lst) == 1:
                return [lst]
            
            all_perms = []
            for i in range(len(lst)):
                # Continue if k > (i + 1) * (n - 1)! -> our answer won't start with lst[i]
                if len(lst) == n and k > (i + 1) * self.n_1_fact:
                    continue
                # Normal permutation logic
                perms_without = genPerms([x for x in lst if x != lst[i]])
                # If we are at the right start element, find result perm and stick lst[i] at the front
                if len(lst) == n:
                    idx = k - i * self.n_1_fact - 1
                    self.res = "".join([str(x) for x in [lst[i]] + perms_without[idx]])
                    return []
                # Otherwise just normal permutation code
                perms_with = []
                for perm in perms_without:
                    perms_with.append([lst[i]] + perm)
                all_perms += perms_with
            return all_perms
        
        genPerms([x for x in range(1, n + 1)])
        return self.res
22800