Skip to content

Commit cc85c58

Browse files
committed
kth permutation
1 parent d7f4442 commit cc85c58

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include<iostream>
2+
#include<vector>
3+
using namespace std;
4+
// Brute force is to generate all possible permutations; sort then find value at k-1th element;
5+
string getPermutation(int n, int k) {
6+
vector<int> nums;
7+
string ans;
8+
int fact = 1;
9+
for (int i = 1; i <= n; i++) {
10+
nums.push_back(i); // create set for 1,2,3....n
11+
fact *= i; // n!
12+
}
13+
k--; // 0-based indexing
14+
while (nums.size()) {
15+
fact /= nums.size(); // reduce factorial as one element is reuced;
16+
int loc = k / fact;
17+
ans += to_string(nums[loc]); // 1|{234} -> 3!=6 same for 2,3,4
18+
nums.erase(nums.begin() + loc); // erase the picked element
19+
k %= fact; // k lies in this group of (n-1)! so find new index of k
20+
}
21+
return ans;
22+
}
23+
int main() {
24+
int n = 7;
25+
int k = 1000;
26+
cout << getPermutation(n, k) << endl;
27+
return 0;
28+
}

0 commit comments

Comments
 (0)