LeetCodes——60. Permutation Sequence【排列问题】

题目要求

The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
“123”
“132”
“213”
“231”
“312”
“321”
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
[1,2,3……n]的集合一共有n!个排列,如果全排列按照上述序列排序的话,给定n和k,返回第k个排列数。

解题思路

这道题一开始就想用DFS来搜索,因为DFS的搜索路径和排列的顺序是相同的,在搜索过程中,记录下排列数的个数,一旦个数等于k,则返回。

DFS代码(超时)
class Solution {
public:
    string getPermutation(int n, int k) {
        string tmp = "";
        vector<bool> visited(n,false);
        int count = 0;
        dfs(count,tmp,n,k,visited);
        return tmp;
    }
    void dfs(int &count, string &tmp, int n, int k, vector<bool> visited){
        if (tmp.length() == n){
            count++;
            return;
        }
        for (int i=0;i<n;i++){
            if (!visited[i]){
                tmp+=i+'1';
                visited[i] = true;
                dfs(count,tmp,n,k,visited);
                if (count == k){//一旦count为k时,则返回
                    break;
                }
                visited[i] = false;
                tmp.erase(tmp.end()-1);
            }
        }
        return;
    }
};

在网上查阅到大神代码,用的是数学方法。思路如下:

1.n个数字的排列方法一共是n!个,如果当确定了第一位数字后,后续n-1个数组的排列方法是(n-1)!种。因此,n个数字的排列方法一共是nx(n-1)!种。
2.第k个排列数,首先确定第一位的数,比如以1开头一共是(n-1)!个,以2开头一共是(n-1)!个……以此类推。因此,k/(n-1)!+1可得到排列数k的第一位数。
3.已知排列数k的第一位数之后,它在以这位数开头的数组中排列第几呢?可用k%(n-1)!+1得到。
4.由3中所得,因此我们需要去求在n-1个数字中在k%(n-1)!+1上的数。这就回到了最开始的问题,在n个排列数中求第k个数。

AC代码
class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> s(n,0);
        string res = "";
        int factor = 1;
        for (int i=2;i<=n-1;i++){
            factor*=i;//(n-1)!
        }
        for (int i=0;i<n;i++){
            s[i] = i+1;
        }
        k--;
        int round = n-1;
        while (round >= 0){
            int num = s[k/factor];//确定第一位数
            res += (num+'0');
            s.erase(s.begin() + k/factor);
            if (round > 0){
                k %= factor;//得到在n-1个数字中的排列位置。
                factor /= round;
            }
            round--;
        }
        return res;
    }
};

结果

200 / 200 test cases passed.
Status: Accepted
Runtime: 9 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值