[leetcode_60]Permutation Sequence

求出[1,2,3,…,n]全排列的第k个数

纯暴力为超时,其实每隔一个数都可以排除一些数,不用每个数每个数的向上搜索。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
    string getPermutation(int n, int k) {
        count = 0;
        flag = new bool[n+1];
        for(int i = 1;i <= n;i++) {
            flag[i] = false;
        }
        string ans = "";
        string result = "";
        for(int i = 1;i <= n;i++) {
            if(result != "") break;
            if(k > factorial(n-1) + count) {
                count += factorial(n-1);
                continue;
            }
            if(flag[i] == false) {
                flag[i] = true;
                ans.push_back(i + '0');
                getPermutationStep(n, k, 1, ans);
                ans.erase(ans.end()-1);
                flag[i] = false;
            }
        }
        return result;
    }
private:
    int count;
    bool *flag;
    string result;
    void getPermutationStep(int n, int k, int now, string ans) {
        if(result != "") return;
        if(now == n) {
            count++;
            if(k <= count) {
                result = ans;
            }
            return;
        }
        for(int i = 1;i <= n;i++) {
            if(flag[i] == false) {
                if(now==1 && k > factorial(n-now-1) + count) {
                    count += factorial(n-now-1);
                    continue;
                }
                flag[i] = true;
                ans.push_back(i + '0');
                getPermutationStep(n, k, now+1, ans);
                ans.erase(ans.end()-1);
                flag[i] = false;
            }
        }
    }
}
int factorial(int x) {
    int ans = 1;
    for(int i = 1;i <=  x;i++) {
        ans *= i;
    }
    return ans;
}
Licensed under CC BY-NC-SA 4.0