標籤: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):
"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.
分析:首先想到的是回溯法的排列樹+計數,但是排列樹並不符合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 };