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

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

Subscribe to see which companies asked this question.

给定n个k,返回全排列中的第k个排列。

二、解题思路:

Medium题。进步了,好像50%多了

思路:

例如 n=3, k=4,首先计算第一个字符应该是几,因为每个字符在第一位的排列数为sum=!(n - 1)个,排列序x = k -1;所以用sum/x=(k-1)/!(n-1)计算出是,第几个数字,如此时(4-1)/!(3-1)= 1 ,所以第一位应该是第一大的数(还有第0大的数)即2;接下来计算第二位上的数,同理,通过取余得到此时的排列序x值 :x=(k-1)%!(n-1),除以此时的排列数sum=!(n-1-1),得到第二位上数应为剩下数中第1大的数即3,以此类推,直到n个字符都加进字符串为止。

(1)创建一个list,把‘1’到‘n’的字符放进去。

(2)计算排列次序x,计算排列数sum,相除得到此时应将剩下数字中的第几大数字加入字符串(加入后将list中的该字符删除),更新相关参数;直到将全部n个字符加入字符串。

三、源码:

import java.util.ArrayList;
import java.util.Arrays;


public class Solution  
{  
	 public String getPermutation(int n, int k)
	 {
		ArrayList<Character> temp = new ArrayList<Character>();
	    String a = "";
	    for (int i = 0; i < n; i++)
	    	temp.add((char)('1' + i));
	    int x = k - 1;
	    while (temp.size() > 1)
	    {
	    	int sum = 1;
	    	for (int j = 1; j < n; j++)
	    		sum *= j;
	    	n--;
	    	a = a + temp.get(x / sum);
	    	temp.remove(x / sum);
	    	x = x % sum;
	    	
	    }
	    a += temp.get(0);
	    return a;
	 }
	
    public static void main(String args[])      
    {      
             
    	
    	int[] nums = {1,1,2};
    	//String word = "ABfS";
        Solution solution = new Solution();     
        System.out.print(solution.getPermutation(5, 72)); 
    }      
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值