[LeetCode] Permutation Sequence

來源:互聯網
上載者:User

標籤:style   class   blog   code   ext   color   

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.

 

分析:首先想到的是回溯法的排列樹+計數,但是排列樹並不符合next_permutation 的關係,所以只能使用時間複雜度O(n^n)的排序樹。。每個位置都有n中可能,記錄下已經使用的數字,然後從未使用的資料中選擇,然後遞迴調用,其實使用的還是回溯法的架構,有所更改。

上Code,但是大數時會逾時。。

 

 1 class Solution { 2         vector<bool> m_avaliable; 3         int m_k; 4         int m_cnt; 5         vector<int> m_array; 6     public: 7         string m_str; 8  9         void dfs_permutation(int size, int dep)10         {11             if(dep == size)12             {13                 m_cnt ++;14                 if(m_cnt == m_k)15                 {16                     for(int i = 0; i < size; i++)17                     {18                         m_str += m_array[i] + ‘1‘;19                     }20                     return;21                 }22             }23 24             //dfs to the next level25             // every level has size choices, its time complexity is O(n^n)26             for(int i = 0; i < size; i++)27             {28                 if( m_avaliable[i] == true)29                 {30                     //cout <<"dep = " <<dep <<endl;31                     //cout <<"i   = " <<i <<endl;32                     m_array[dep] = i;33                     m_avaliable[i] = false;34                     dfs_permutation( size, dep+1);35                     m_avaliable[i] = true;36                 }37 38             }39 40 41 42         }43         string getPermutation(int n, int k)44         {45             //initinalize the member variable46             m_avaliable.resize(n, true);47             m_array.resize(n);48             m_k = k;49             m_cnt = 0;50             m_str.clear();51 52             //call dfs53             dfs_permutation(n, 0);54 55             // return 56             return m_str;57         }58 59 };

 

聯繫我們

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