LeetCode Permutation Sequence,permutationleetcode

來源:互聯網
上載者:User

LeetCode Permutation Sequence,permutationleetcode

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.

題意:找出第k大的序列。

思路:可以想到n個數位全排列是n!,舉個例子(轉的):對於某一個n, k,比如n=4, k=17。首Crowdsourced Security Testing道n以下的組合數有6,2,1。那麼17 = 2*6 + 2*2 + 1,

由於權值6的倍數是2,且有剩餘,所以第4位(最高位)的值是從“1234”中選第3小的數,也就是3;

由於權值2的倍數是2,且有剩餘,所以第3位的值是從“124”中選第3小的數,也就是4;

由於權值1的倍數是1,且沒有剩餘,所以第2位的值是從“12”中選第1小的數,也就是1;

最後剩下數,逆序追加到後面。

class Solution {public:    string remove(string s, int index, char &c) {        c = s[index-1];        string s1 = s.substr(0, index-1);        string s2 = s.substr(index);        return s1 + s2;    }        string getPermutation(int n, int k) {        if (n > 9 || n < 1) return "";                string temp = "123456789";        int A[9] = {1, 2, 6, 24, 120, 720, 5040, 40320, 362880};          if (A[n-1] < k) return "";                string s = temp.substr(0, n);        if (k == 1) return s;        if (k == A[n-1]) {            reverse(s.begin(), s.end());            return s;        }                string ans = "";        char c;        for (int i = n-2; i >= 0; i--) {            int m = 0;            if (k < A[i]) {                s = remove(s, 1, c);                ans += c;                continue;            }            while (k >= A[i]) {                k -= A[i];                m++;            }            if (k == 0) {                s = remove(s, m, c);                ans += c;                reverse(s.begin(), s.end());                return ans + s;            } else {                s = remove(s, m+1, c);                ans += c;            }        }                return ans;    }};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.