The set
Given
[1, 2, 3, ..., n]
contains a total of n!
unique permutations.Given
n
and k
, return the kth
permutation sequence.Example:
Input: n=3,k=3 Output: str="213"
Approach
Java
import java.util.ArrayList;import java.util.Collections;public class PermutationSequence {public static void main(String[] args) {int n = 3, k = 3;System.out.println(getPermutation(n, k));}// method for get permutaion sequencestatic String getPermutation(int n, int k) {//permutation(n, n, k, "");return result;}static String result;static int fac(int i) {if (i == 0)return 1;return i * fac(i - 1);}static void permutation(int org, int n, int k, String per) {if (n == 0) {result = per;return;}ArrayList<Integer> list = new ArrayList<>();for (int i = 1; i <= org; i++) {if (per.indexOf((char) (48 + i)) < 0)list.add(i);}// sort list in ascending orderCollections.sort(list);int currPerm = fac(n);int totalSlices = currPerm / n;int current = 1;int index = 0;int offset = 0;while (current <= currPerm) {if (k >= current && k <= current + totalSlices - 1) {offset = current - 1;break;}current += totalSlices;index++;}int value = list.get(index);// call againpermutation(org, n - 1, k - offset, per + value);}}
C++
#include <bits/stdc++.h>using namespace std;string getPermutation(int n, int k){string x="";for(int i=1;i<=n;i++){x+=to_string(i);}k=k-1;while(k){bool flag=next_permutation(x.begin(),x.end());k--;}return x;}int main(){int n=3,k=3;cout<<getPermutation(n,k);return 0;}
No comments:
Post a Comment