zoukankan      html  css  js  c++  java
  • 60 Permutation Sequence

    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.
    

    解析

    • 这题不可以用递归的解法,否则不管怎么优化都会超时,这题时间卡得很紧啊。。。之前一直在优化递归,从几百毫秒优化到 9 毫秒依然不行。遂放弃,上网学习大神的解法,才发现这题是有数学技巧的。
    • 具体来说是:n 个数字有 n!种全排列,每种数字开头的全排列有 (n - 1)!(n!/ n)种。所以用 k / (n - 1)! 就可以得到第 k 个全排列是以第几个数字开头的。用 k % (n - 1)! 就可以得到第 k 个全排列是某个数字开头的全排列中的第几个。这又变成了最初的问题设置。
    • 对于以某个数字开头的全排列(第一个数字固定后的全排列,不再理会第一个数字),它有 (n - 1)! 种全排列,那么这些全排列中,每个数字开头的全排列有 (n - 2)! ((n-1)! / (n-1))。
      依次类推。
    // 60. Permutation Sequence
    class Solution_60 {
    public:
    	string getPermutation(int n, int k) {
    
    		vector<int> vec;
    		for (int i = 0; i < n;i++)
    		{
    			vec.push_back(i + 1);
    		}
    		
    		for (int i = 0; i < k-1;i++)
    		{
    			next_permutation(vec.begin(), vec.end());
    		}
    
    		string res;
    		for (int i = 0; i < vec.size();i++)
    		{
    			char temp = vec[i] + '0';
    			res.push_back(temp);
    		}
    		
    		return res;
    	}
    
    	string getPermutation_ref(int n, int k) {
    		vector<int> permutation(n + 1, 1);
    		for (int i = 1; i <= n; ++i) {
    			permutation[i] = permutation[i - 1] * i;
    		}
    		vector<char> digits = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    		int num = n - 1;
    		string res;
    		while (num) {
    			int t = (k - 1) / (permutation[num--]);
    			k = k - t * permutation[num + 1];
    			res.push_back(digits[t]);
    			digits.erase(digits.begin() + t);
    		}
    		res.push_back(digits[k - 1]);
    		return res;
    	}
    
    };
    

    题目来源

  • 相关阅读:
    ITUT P.862 (PESQ)
    著名音频技术猎头的主页JOBS IN PRO AUDIO
    把自己的总结贴出吧:音频编码 上
    在网页上嵌入 PowerPoint 演示文稿
    Dwing吧,讨论编解码系统应用
    刘品今天推荐了一个speech codec:hawkvoice
    测试网页上使用PPT:特殊贴
    ITUT P.863 (POLQA)
    转帖:面向SACD的DXD技术之优势
    转帖:纪念我的发烧历程
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8602732.html
Copyright © 2011-2022 走看看