60. Permutation Sequence(unsolved)

来源:互联网 发布:音频算法工程师 编辑:程序博客网 时间:2024/06/05 19:14

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.

class Solution {public:    string getPermutation(int n, int k) {    int i,j,f=1;    // left part of s is partially formed permutation, right part is the leftover chars.    string s(n,'0');    for(i=1;i<=n;i++){        f*=i;        s[i-1]+=i; // make s become 1234...n    }    for(i=0,k--;i<n;i++){        f/=n-i;        j=i+k/f; // calculate index of char to put at s[i]        char c=s[j];        // remove c by shifting to cover up (adjust the right part).        for(;j>i;j--)            s[j]=s[j-1];        k%=f;        s[i]=c;    }    return s;}};

二刷时
由于上面这种做法我不理解,所以就按照自己做法做了,注意我这种做法会超时的。思路就是先把所有的情况用回溯法都存起来,然后sort排序,再取第k-1个

class Solution {public:    vector<string> result;    string getPermutation(int n, int k) {        string str="";        for(int i=1;i<=n;i++)            str=str+to_string(i);        solve(str,0,str.size());        sort(result.begin(),result.end());        return result[k-1];    }    void solve(string str,int begin,int end){        if(begin==end)        {            //cout<<str<<endl;            result.push_back(str);            return ;        }        for(int i=begin;i<end;i++)        {            swap(str[begin],str[i]);            solve(str,begin+1,end);            swap(str[begin],str[i]);        }        return ;    }};
0 0
原创粉丝点击