Leetcode: 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):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

解答:

这道题让人想到可以使用Leetcode中 Next Permutation的方法,并使用该方法迭代k - 1次,则得到结果。但是OJ的结果是Time Limit Exceeded.

代码: 

class Solution {
        string nextPermutation(string str) {
            if(str.length() < 2)
                return str;
                
            int i = -1, j;
            for(i = str.length() - 2; i >= 0; i--)
            {
                if(str[i] < str[i + 1])
                    break;
            }
           if(i > -1)
           {
                for(j = str.length() - 1; j > i; j--)
                {
                    if(str[j] > str[i])
                        break;
                }
           
                char t = str[i];
                str[i] = str[j];
                str[j] = t;
           }
           i++;
           for(int j = 0; j < (str.length() - i) / 2; j++)
           {
               char t = str[i + j];
               str[i + j] = str[str.length() - j - 1];
               str[str.length() - j - 1] = t;
           }
           return str;
    }
public:
    string getPermutation(int n, int k) {
        string str;
        for(int i = 1; i < n + 1; i++)
            str.append(1, i + '0');
            
        for(int i = 0; i < k - 1; i++)
            str = nextPermutation(str);
            
        return str;
    }
};

思路二:

从例子中寻找一个规律,假设numbers = {1, 2, 3}, 那么在全排列序列中,第一个元素是(k  - 1 )/ (n - 1)! + 1, 在numbers中下标是(k  - 1 )/ (n - 1)! . 将该元素从Numbers中取出,append到结果字符串,并且将numbers中该元素从numbers中删除。这个规律可以类推下去,在numbers中剩余元素中依次选择出结果字符串中下标为1,....,n - 1的元素。

代码:

class Solution {
      
public:
    string getPermutation(int n, int k) {
                // create a factorial map
        string ret;
        vector<int> numbers(n);
        int product = 1;
        for(int i = 0; i < n; i++)
        {
            numbers[i] = i + 1;
            product *= (i + 1);
        }
        k = k - 1;
        product /= n;
        
        for(int i = 0; i < n - 1; i++)
        {
            int select = (k / product);
            ret.append(1, '0' + numbers[select]);
            numbers.erase(numbers.begin() + select);
            k = k % product;
            product /= (n - i - 1);
        }

        ret.append(1, '0' + numbers[0]);
        return ret;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值