← Home

60. Permutation Sequence

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
backtrackingC++Markdown
60

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 60. Permutation Sequence, the solution in this repository is mainly a backtracking solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: backtracking.

The notes already sitting in the source point us in the right direction:

  • backtracking
  • TLE
  • 126 / 200 test cases passed.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack, getPermutation, used, nums.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//backtracking
02//TLE
03//126 / 200 test cases passed.
04class Solution {
05public:
06    string ans;
07    
08    void backtrack(int n, int k, string& s, vector<bool>& used, int& seq){
09        if(s.size() == n){
10            // cout << s << ", " << seq << endl;
11            if(seq == k){
12                ans = s;
13            }
14            ++seq;
15        }else{
16            for(int i = 0; i < n; ++i){
17                if(!used[i]){
18                    s += (i+1+'0');
19                    used[i] = true;
20                    backtrack(n, k, s, used, seq);
21                    s.pop_back();
22                    used[i] = false;
23                }
24                if(ans != "") break;
25            }
26        }
27    }
28    
29    string getPermutation(int n, int k) {
30        string s = "";
31        vector<bool> used(n, false);
32        int seq = 1;
33        backtrack(n, k, s, used, seq);
34        return ans;
35    }
36};
37
38//backtracking + math
39//Runtime: 4 ms, faster than 48.53% of C++ online submissions for Permutation Sequence.
40//Memory Usage: 5.9 MB, less than 83.89% of C++ online submissions for Permutation Sequence.
41class Solution {
42public:
43    string ans;
44    
45    vector<int> facts;
46    
47    void backtrack(int n, int k, string& s, vector<bool>& used, int& seq){
48        if(s.size() == n){
49            // cout << s << ", " << seq << endl;
50            if(seq == k){
51                ans = s;
52            }
53            ++seq;
54        }else if(seq + facts[n-s.size()-1] < k){
55            //skip the permutations formed by the remaining n-s.size() chars
56            seq += facts[n-s.size()-1];
57        }else{
58            for(int i = 0; i < n; ++i){
59                if(!used[i]){
60                    s += (i+1+'0');
61                    used[i] = true;
62                    backtrack(n, k, s, used, seq);
63                    s.pop_back();
64                    used[i] = false;
65                }
66                if(ans != "") break;
67            }
68        }
69    }
70    
71    string getPermutation(int n, int k) {
72        string s = "";
73        vector<bool> used(n, false);
74        int seq = 1;
75        
76        facts = vector<int>(n);
77        facts[0] = 1;
78        for(int i = 2; i <= n; ++i){
79            facts[i-1] = facts[i-2] * i;
80        }
81        
82        backtrack(n, k, s, used, seq);
83        return ans;
84    }
85};
86
87//math
88//https://leetcode.com/problems/permutation-sequence/discuss/22507/%22Explain-like-I'm-five%22-Java-Solution-in-O(n)
89//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Permutation Sequence.
90//Memory Usage: 5.9 MB, less than 86.08% of C++ online submissions for Permutation Sequence.
91//time: O(N)
92class Solution {
93public:
94    string getPermutation(int n, int k) {
95        string ans = "";
96        
97        vector<int> nums(n);
98        iota(nums.begin(), nums.end(), 1);
99        
100        int fact = 1;
101        for(int i = 1; i <= n; ++i){
102            fact *= i;
103        }
104        
105        --k; //1-based -> 0-based
106        for(int i = 0; i < n; ++i){
107            //there could be (n-1)! permutations if we exclude one char
108            fact /= (n-i);
109            //the kth permutation belongs to what group
110            int groupid = k/fact;
111            ans += (nums[groupid] + '0');
112            nums.erase(nums.begin()+groupid);
113            //there are "groupid" groups before the visited group
114            k -= fact * groupid;
115        }
116        
117        return ans;
118    }
119};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.