Leetcode 60. Permutation Sequence (Medium) (cpp)

来源:互联网 发布:80端口被屏蔽 编辑:程序博客网 时间:2024/06/15 23:06

Leetcode 60. Permutation Sequence (Medium) (cpp)

Tag: Backtracking, Math

Difficulty: Medium


/*60. Permutation Sequence (Medium)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;string s(n, '0');for (i = 1;i <= n;i++) {f *= i;s[i - 1] += i;}for (i = 0, k--; i < n; i++) {f /= n - i;j = i + k / f;char c = s[j];for (;j > i;j--) {s[j] = s[j - 1];}k %= f;s[i] = c;}return s;}};


0 0
原创粉丝点击