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 (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k th, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

我剛開始嘗試著把,所有的全排列都列出來,然后,找到對應位置的內容,但是這樣效率太低,直接超時了,上網差了一下,和數學有關系。。。這題打算先放一放,放一下別人的代碼吧。

public String getPermutation(int n, int k) {
            char[] nums = new char[]{'1','2','3','4','5','6','7','8','9'};
            String tmp = "";
            for(int i=0;i<n;i++) {
                tmp += nums[i];
            }
            StringBuffer s = new StringBuffer(tmp);
            String r = "";
            while(k>0&&!s.toString().equals("")) {
                // 計算 (n-1)的排列個數cnt
                int cnt = 1, i = s.length()-1;
                while(i > 1) {
                    cnt*=i;
                    i-=1;
                }
                int pos = (k-1)/cnt;
                r += s.charAt(pos);
                s = s.deleteCharAt(pos);
                k -= pos * cnt;
            }
            return r;
        }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容