Permutation Sequence

本文介绍了一种算法,用于找出1到n的所有排列中的第k个排列。通过将排列按(n-1)!分组,利用递归思想找到每组中的元素,最终得到目标排列。

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, return the kth permutation sequence.

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

Show Tags

Have you met this question in a real interview?

思路: 这个排列是按照 (n - 1) ! 来排列的, 每一层都有( n - 1 ) ! 个 数字, 因此我们要找到是第 selectI 个 要先 除以 (n - 1) !, 然后找到在没使用的数字中 的 第  selectI 个 数字, 并设置为已经使用。 最后如果 到了 第1 个,把剩余的没使用的数字按顺序插入。

易错点:  1 .  k 一开始要  减1 。

2. level  每次 要除以 n - i ;   i  从1 到 n - 1

public class Solution {
    public String getPermutation(int n, int k) {
		boolean[] used = new boolean[n + 1];
		StringBuilder buffer = new StringBuilder();
		used[0] = true;
		int level = 1;
		for (int i = 1; i < n; ++i) {
			level *= i;// 阶乘的当前level 
		}
		k = k - 1;//-----非常重要
		for (int i = 1; i < n; ++i) {
			int selectI = k / level;
			for(int j = 1; j <= n; j++){
				if(!used[j]){
					selectI--;
				}
				if(selectI == -1){
					used[j] = true;
					buffer.append(j);
					break;
				}
			}
			k = k % level;//-----
			level /= (n - i);//--- 从 n - 1 , 除到 1, 阶乘 反向除下去
		}
		
		for(int i = 1; i <= n; i++){// 把还没用过的数字按顺序 插入
			if(!used[i]){
			    used[i] = true;
				buffer.append(i);
				break;
			}
		}
		return new String(buffer);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值