60. Permutation Sequence

来源:互联网 发布:淘宝充值平台进价表 编辑:程序博客网 时间:2024/04/18 11:50

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):

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

Given n and k, return the kth permutation sequence.


思路: 将元素按从小到大的顺序保存在list中,从第一个开始判断应该是什么数字,依次根据下标从list中选取数据,然后删除已用的数据.


code:

public class Solution {
    public String getPermutation(int n, int k) {
        StringBuilder res=new StringBuilder("");
        int all=1;
        int temp=n-1;
        List<Integer> list=new ArrayList<Integer>();
        for(int i=1;i<=n;i++)
            list.add(i);
        while(temp>1)
            all*=(temp--);
         
        for(int i=0;i<n-1;i++){
            temp=(k-1)/all;// 注意这里是k-1
            res.append(list.get(temp));
            list.remove(temp);
            k-=temp*all;
            all/=(n-i-1);
        }
        res.append(list.get(0));
        return res.toString();
    }
}

0 0
原创粉丝点击