首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Backtracking - 60. Permutation Sequence

Backtracking - 60. Permutation Sequence

作者头像
ppxai
发布2020-09-23 17:32:34
发布2020-09-23 17:32:34
4050
举报
文章被收录于专栏:皮皮星球皮皮星球

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 for n = 3:

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

Given n and k, return the _k_th permutation sequence.

Note:

  • Given n will be between 1 and 9 inclusive.
  • Given k will be between 1 and n! inclusive.

Example 1:

代码语言:javascript
复制
Input: n = 3, k = 3
Output: "213"

Example 2:

代码语言:javascript
复制
Input: n = 4, k = 9
Output: "2314"

思路:

题目意思是给一个整数n,求出1-n内所有组合的第k大的组合,最直观的方法可以使用回溯,把所有的结果都求出来再去找第k大, 但是这一题可以用其他技巧解决,因为是由n的阶乘,所以很容易得出:f[i] = f[i-1]*i,只要通过阶乘来判断要找到的数在最高位之外的数的所有组合中的位置,就能得到结果。

代码:

go:

代码语言:javascript
复制
func getPermutation(n int, k int) string {

    var res int 
    var nums []int
    var fact = 1
    for i := 1; i <= n; i++ {
        fact *= i
        nums = append(nums, i)
    }
    
    l := k - 1
    for i := 0; i < n; i++ {
        fact /= (n - i)
        idx := (l / fact)
        res = res * 10 + nums[idx]
        nums = append(nums[0:idx], nums[idx+1:]...)
        l -= idx * fact
    }
    
    return strconv.Itoa(res)
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年09月09日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档