[LeetCode]60. Permutation Sequence
題目描述:
The set [1,2,3,...,n]
contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence 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.
-
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
題解
該題其實本質上是一個找規律的題,我們可以試圖列出n=4是的全排列,從中一探究竟
- 1 2 3 4
- 1 2 4 3
- 1 3 2 4
- 1 3 4 2
- 1 4 2 3
- 1 4 3 2
- 2 1 3 4
- 2 1 4 3
- 2 3 1 4
- 2 3 4 1
- 2 4 1 3
- 2 4 3 1
- 3 1 2 4
- 3 1 4 2
- 3 2 1 4
- 3 2 4 1
- 3 4 1 2
- 3 4 2 1
從上面的排列可以看出:
第一位每個數字出現次數為6次=3!=(n-1)!
第一位數字確定之後,第二位中剩下的每個數字出現的次數為2次=2!=(n-2)!
第一二位數字確定之後,第三位中剩下的每個數字出現的次數為1次=1!=(n-3)!
第一二三位數字確定之後,第四位中剩下的每個數字出現的次數為1次=0!=(n-4)!
假設將1-->n儲存到一個陣列中,那麼k-th排列的
第一位為陣列元素中的第(k/{(n-1)!})位置,取出該元素之後應該將該元素從陣列中刪除,然後對k應該更新為k%(n-1)!
第二位為陣列元素中的第 (k/{(n-2)!})位置,取出對應元素之後應該將該元素從陣列中刪除,然後將k更新為k%(n-2)!
...
迴圈直到第n位為止
在迴圈中多次用到階乘,因此我們可以將0-(n-1)的階乘提前算出儲存到一個陣列中
為了便於操作(存在多次(n-1)元素的刪除操作)我們將使用一個ArrayList來進行儲存參與排列的數
具體的程式碼如下
public String getPermutation(int n, int k) {
String res="";
//初始化階段
List<Integer> numbers = new ArrayList<>();
int[] factorial = new int[n];
for(int i=1;i<=n;i++) {
//將排列用到的數字先存到一個list中
numbers.add(i);
//將階乘先存到陣列裡
if(i==1) {
factorial[i-1]=i;
}else {
factorial[i-1]=(i-1)*factorial[i-2];
}
}
--k;
//核心部分
for(int i=1;i<=n;i++) {
int index = k/factorial[n-i];
res+=numbers.get(index);
numbers.remove(index);
k%=factorial[n-i];
}
return res;
}
相關文章
- 【leetcode】60. Permutation Sequence 全排列的第k位序的排列形式LeetCode
- Leetcode 31 Next PermutationLeetCode
- LeetCode 444 sequence reconstructionLeetCodeStruct
- Leetcode 298 Binary Tree Longest Consecutive SequenceLeetCode
- Girl Permutation
- sequence to sequence模型模型
- [LintCode] Permutation in String
- G - Ban Permutation
- next_permutation
- C. Game on PermutationGAM
- Yet Another Permutation ConstructiveStruct
- Codeforces 452F Permutation
- next_permutation函式函式
- Sequence recognition
- Codeforces_943_D_Permutation GameGAM
- [ARC176D] Swap Permutation
- CF1946E Girl Permutation
- 精讀《Permutation, Flatten, Absolute...》
- [CF1718D] Permutation for Burenka 瞎扯
- codeforces 1284C New Year and Permutation
- AtCoder Beginner Contest 282 G - Similar PermutationMILA
- uvm的sequence
- PostgreSQL 序列(Sequence)SQL
- ORACLE SEQUENCE用法Oracle
- python sequence序列Python
- Rainbow Bracket SequenceAIRacket
- Increasing Sequence with Fixed OR
- PostgreSQL sequence (一)SQL
- 論文閱讀:Sequence to sequence learning for joint extraction of entities and relations
- hdu 6446 Tree and Permutation(dfs+思維)
- Solution - Atcoder ARC114F Permutation Division
- FSM:Sequence 1101 recognizer
- F - Two Sequence Queries
- 裁剪序列Cut the Sequence
- DeepLearning – Overview of Sequence modelView
- E. Block SequenceBloC
- mysql實現sequenceMySql
- solution-2022 CCPC Guilin J. Permutation PuzzleGUI