leetcode - Permutation Sequence
2013-12-07 12:08 张汉生 阅读(124) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 string getPermutation(int n, int k) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 string rlt=""; 7 unsigned *facts = new unsigned[n+1]; 8 unsigned * arr = new unsigned[n]; 9 facts[0] = 1; 10 for (int i=1; i<=n; i++){ 11 facts[i] = facts[i-1] * i; 12 arr[i-1] = i; 13 } 14 k = k-1; 15 for (int i=1; i<n; i++){ 16 int offset = k/facts[n-i]; 17 int tmp = arr[i-1+offset]; 18 for (int j=i-1+offset; j>=i; j--){ 19 arr[j] = arr[j-1]; 20 } 21 arr[i-1] = tmp; 22 k = k % facts[n-i]; 23 } 24 for (int i=0; i<n; i++) 25 rlt = rlt + (char)('0'+arr[i]); 26 delete []arr; 27 delete []facts; 28 return rlt; 29 } 30 };