[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
- Permutation Sequence leetcode javaLeetCodeJava
- Leetcode 31 Next PermutationLeetCode
- Leetcode-Next PermutationLeetCode
- Next Permutation leetcode javaLeetCodeJava
- LeetCode-Palindrome Permutation IILeetCode
- Leetcode-Permuation SequenceLeetCode
- [LeetCode] Next Permutation 下一個排列LeetCode
- LeetCode 444 sequence reconstructionLeetCodeStruct
- LeetCode-Repeated DNA SequenceLeetCode
- Leetcode-Longest Consecutive SequenceLeetCode
- Longest Consecutive Sequence leetcode javaLeetCodeJava
- 60. 電子郵件
- LeetCode128:Longest Consecutive SequenceLeetCode
- Girl Permutation
- Leetcode 298 Binary Tree Longest Consecutive SequenceLeetCode
- LeetCode- Binary Tree Longest Consecutive SequenceLeetCode
- G - Ban Permutation
- sequence to sequence模型模型
- C. Game on PermutationGAM
- next_permutation
- Yet Another Permutation ConstructiveStruct
- [LintCode] Permutation in String
- Codeforces 452F Permutation
- next_permutation函式函式
- [ARC176D] Swap Permutation
- ORACLE SEQUENCEOracle
- Sequence recognition
- Codeforces_943_D_Permutation GameGAM
- CF1946E Girl Permutation
- ORACLE SEQUENCE用法Oracle
- PostgreSQL 序列(Sequence)SQL
- PostgreSQL sequence (一)SQL
- Oracle - Sequence序列Oracle
- Oracle Sequence NocacheOracle
- Oracle序列sequenceOracle
- 【轉】MySQL中增加sequence管理功能(模擬建立sequence)MySql
- 聊聊CBO的連線排列(Join Permutation)