LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目連結: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.

這道題的要求是返回由n個數排列組成的第k個序列(n範圍是1~9)。

這道題的標籤有回溯和數學,可是試了下回溯產生第k個(k已經對n!模數了)序列,逾時。又試了試next_permutation函數,還是逾時。。。不知道用回溯怎麼做這道題。。。

不過,這確實是一道地地道道的數學問題。考慮到n個不同數的排列總共有n!種,也就是n-1個數的排列共有(n-1)!種,所以n個數的第k個排列的第一位元字取決於k中包含多少個(n-1)!,即k / (n-1)!。以此類推,第i位上的數字就是剩餘k / (n-1-i)!位置上的數字(剩餘k是由於k每次對(n-1-i)!模數)。所以只要當前的k除以(n-1-i)!,得到的數字就是當前剩餘數組的位置的索引j。接下來取出該位置元素,並將該位置於i之間的元素都後移1個位置即可。

實現的時候,k首先需要減1,因為第1個已經產生了,也就是要在第1個的基礎上產生第k-1個排列。而用f記錄n!。

時間複雜度:O(n2)

空間複雜度:O(n)

 1 class Solution 2 { 3 public: 4     string getPermutation(int n, int k) 5     { 6         string s(n, '0'); 7          8         int i, j, f = 1; 9         for(i = 0; i < n; ++ i)10         {11             s[i] += i + 1;12             f *= i + 1;13         }14         15         for(i = 0, k = (k - 1) % f; i < n; ++ i, k %= f)16         {17             f /= n - i;18             19             int j = i + k / f;20             char c = s[j];21             while(j > i)22                 s[j] = s[-- j];23             s[i] = c;24         }25         26         return s;27     }28 };

轉載請說明出處:LeetCode --- 60. Permutation Sequence

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.