tarunreddy1018

Kth Permutation Sequence

Jun 8th, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. public class Solution {
  2. private long factorial[];
  3.  
  4. private void getPermutationRecursively(int A,long B,int index,boolean available[],StringBuilder result) {
  5. if(index == A+1) {
  6. return;
  7. }
  8.  
  9. for(int i = 1;i <= A;i++) {
  10. if(available[i]) {
  11. long fact = factorial[A-index];
  12. B -= fact;
  13. if(B <= 0) {
  14. result.append(i);
  15. available[i] = false;
  16. getPermutationRecursively(A,B+fact,(index+1),available,result);
  17. return;
  18. }
  19. }
  20. }
  21. }
  22.  
  23. public String getPermutation(int A, int B) {
  24. boolean available[] = new boolean[A+1];
  25. factorial = new long[A+1];
  26. factorial[0] = 1;
  27. factorial[1] = 1;
  28. for(int i = 2;i <= A;i++) {
  29. factorial[i] = factorial[i-1]*i;
  30. }
  31.  
  32. StringBuilder result = new StringBuilder();
  33. Arrays.fill(available,true);
  34. getPermutationRecursively(A,B,1,available,result);
  35. return result.toString();
  36. }
  37. }
Add Comment
Please, Sign In to add comment