Skip to content

Commit

Permalink
added 108. Permutation Sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Feb 2, 2015
1 parent df8e128 commit 00c8a99
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
10 changes: 10 additions & 0 deletions 108. Permutation Sequence/TEST.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#define CATCH_CONFIG_MAIN
#include "../Catch/single_include/catch.hpp"
#include "solution.h"

TEST_CASE("Permutation Sequence", "[getPermutation]")
{
Solution s;
REQUIRE( s.getPermutation(3, 5) == "312" );
REQUIRE( s.getPermutation(8, 31492) == "72641583" );
}
24 changes: 24 additions & 0 deletions 108. Permutation Sequence/solution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include <string>
using std::string;
#include <numeric>

class Solution {
public:
string getPermutation(int n, int k) {
int table[10] = {1};
for (int i=1; i<=9; ++i)
table[i] = i*table[i-1];

string dict(n, ' '), ret(dict);
std::iota(dict.begin(), dict.end(), '1');

for (int i=0; n>0; --n) {
int pos = (k-1)/table[n-1];
ret[i++] = dict[pos];
dict.erase(dict.begin()+pos);
k = k - pos * table[n-1];
}
return ret;
}

};

0 comments on commit 00c8a99

Please sign in to comment.