Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- private long factorial[];
- private void getPermutationRecursively(int A,long B,int index,boolean available[],StringBuilder result) {
- if(index == A+1) {
- return;
- }
- for(int i = 1;i <= A;i++) {
- if(available[i]) {
- long fact = factorial[A-index];
- B -= fact;
- if(B <= 0) {
- result.append(i);
- available[i] = false;
- getPermutationRecursively(A,B+fact,(index+1),available,result);
- return;
- }
- }
- }
- }
- public String getPermutation(int A, int B) {
- boolean available[] = new boolean[A+1];
- factorial = new long[A+1];
- factorial[0] = 1;
- factorial[1] = 1;
- for(int i = 2;i <= A;i++) {
- factorial[i] = factorial[i-1]*i;
- }
- StringBuilder result = new StringBuilder();
- Arrays.fill(available,true);
- getPermutationRecursively(A,B,1,available,result);
- return result.toString();
- }
- }
Add Comment
Please, Sign In to add comment