60. 排列序列 Permutation Sequence

题目 <https://leetcode-cn.com/problems/permutation-sequence/>

int mul[] = {0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};

void reverse(char *s,int s_len){
    int i,j;
    char c;
    for(i=0,j=s_len-1;i<j;i++,j--){
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

char * getPermutation(int n, int k){
    char *s = malloc(sizeof(char) * (n+1));
    int i,j,m;
    for(i=0;i<n;i++){
        s[i] = '0'+i+1;
    }
    s[i] = '\0';

    for(i=n-1;i>0;i--){
        j = (k-1)/(mul[i]);
        //printf("%d,%d,%d\n",i,k,j);
        m = s[j];
        memmove(&s[j],&s[j+1],i-j);
        s[i] = m;
        k =  (k-1)% mul[i] +1;
    }
    
    reverse(s,n);
    return s;
}

猜你喜欢

转载自blog.csdn.net/ZRXSLYG/article/details/112262886