首页 > 代码库 > [leetcode]Permutation Sequence
[leetcode]Permutation Sequence
问题描述:
The set [1,2,3,…,n]
contains a total ofn! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
基本思想:
根据k和n!之间的关系,第k个序列应该在哪些位置提升几个数字。
代码:
//consider if k > n! ? string getPermutation(int n, int k) { //C++ //the first vector<char> base(n,'0'); for(int i = 1; i<=n; i++) base[i-1] = i +'0'; vector<int> multi(n); int temp = 1; multi[0] = 1; for(int i =1; i < n; i++){ temp *= i; multi[i] = temp; } k--; for(int i = 0; i< n-1; i++){ int temp = k/multi[n-i-1]; int pos = i+temp; char c = base[pos]; for(int j =pos-1 ; j>=i; j-- ) base[j+1] = base[j]; base[i] = c; k = k%multi[n-i-1]; } //to String string result = ""; for(int i = 0; i < n; i++) result += (base[i]); return result; }
[leetcode]Permutation Sequence
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。