int getFactorial(int n) { int factorial[10] = {-1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; return factorial[n]; } int checkFactorial(int n){ // n is small, use liner search. int factorial[10] = {-1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; for (int i = 1; i < 10; ++i) { if(n >= factorial[i] && n < factorial[i + 1]) return i; } return 0; } void nextPermutetion(string &num) { int i = num.size() - 1; while (i >= 1) { if(num[i] > num[i - 1]) { --i; int ii = num.size() - 1; while (ii > i && num[ii] <= num[i]) --ii; if(ii > i) { swap(num[i], num[ii]); reverse(num.begin() + i + 1, num.end()); break; } } else --i; } } string getPermutation(int n, int k) { if(k > getFactorial(n)) return ""; if(k <= 0 || 0 > n || n >= 10) return ""; //init the permutation. string permu(n,'0'); for(int i = 0; i < n; ++i) permu[i] = i + 1 + '0'; if(k == 1) return permu; while (k > 0) { int fac = checkFactorial(k); //adjust if(permu[n - 1] <= permu[n - fac]) { nextPermutetion(permu); } reverse(permu.begin() + (n - fac), permu.end()); k -= getFactorial(fac); } return permu; }
【leetcode】 Permutation Sequence,布布扣,bubuko.com
【leetcode】 Permutation Sequence
原文地址:http://blog.csdn.net/shiquxinkong/article/details/27959905