60. Permutation Sequence

Description

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 (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.

Solution

Iteration

很巧妙的找規(guī)律題。假設(shè)n = 4, k = 15,所有可能的permutation則是:

  • 1 + {2, 3, 4};
  • 2 + {1, 3, 4};
  • 3 + {1, 2, 4};
  • 4 + {1, 2, 3};

那么每組的組合數(shù)即3! = 6。首先決定第一位,通過15 / 6 = 2,得知第一位應(yīng)該是3。然后題目變成了在{1, 2, 4}中找到k = 15 - 2 * 6 = 3的permutation。
巧妙之處在于用一個candidates list保存尚未被用過的數(shù)字,在每一個迭代中根據(jù)計算出的index去在list中進(jìn)行索引,然后將該數(shù)字移出candidates即可。

class Solution {
    public String getPermutation(int n, int k) {
        int[] factorial = new int[n + 1];
        factorial[0] = 1;
        for (int i = 1; i <= n; ++i) {
            factorial[i] = i * factorial[i - 1];
        }
        
        List<Integer> candidates = new ArrayList<>();
        for (int i = 1; i <= n; ++i) {
            candidates.add(i);
        }
        
        StringBuilder permutation = new StringBuilder();
        --k;    // important! Because k starts from 1, not 0
        
        for (int i = 0; i < n; ++i) {   // fill ith digit
            int index = k / factorial[n - i - 1];
            permutation.append(candidates.get(index));     // elegant
            candidates.remove(index);
            k -= index * factorial[n - i - 1];
        }
        
        return permutation.toString();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容