60. permutation sequence leetcode python

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.

I post two methods.. the first one is brute force. which is N! time.

the second one is linear time.

input fac = (n-1)!

k = k -1

1. get the value from the candidate sequences with fac and K

2. remove the value

3 decrease k with k%fac and fac = fac/i

## num, val, res visit
def backtrack(num, val, res, visit, k):
	if len(val) == len(num):
		res.append(val)
		return 
	for i in range(len(num)):
		if visit[i] == False:
			visit[i] = True
			backtrack(num, val + [num[i]], res, visit, k)
			visit[i] = False




num = [1, 2, 3]
val = []
res = []
visit = [False for i in range(len(num))]
#print range(1,10)
#backtrack(num, val, res, visit, 2)
def getRes(n, k):
	num = range(1,10)
	fac = 1
	k -= 1
	res = []
	for i in range(1, n):
		fac *= i
	for i in reversed(range(n)):
		res.append(str(num[k / fac]))
		num.remove(num[k / fac])
		if i != 0:
			k = k % fac
			fac /= i
	return "".join(res)




print getRes(3, 3)




### Python中NumPy库`random.permutation`函数的使用 #### 函数概述 `np.random.permutation(x)`用于随机排列序列。如果传入的是整数,则会先构建一个从 `0` 到该整数值减一的数组再进行随机排列;如果是多维数组则只沿第一个轴打乱元素置[^1]。 #### 使用示例 ##### 示例 1:对列表或一维数组执行随机排列 当输入为一维数组时,将会返回一个新的含有相同元素但是顺序被打乱的一维数组: ```python import numpy as np arr = np.array([1, 2, 3, 4, 5]) permuted_arr = np.random.permutation(arr) print("原始数组:", arr) print("随机排列后的数组:", permuted_arr) ``` 上述代码可能会输出如下结果: ``` 原始数组: [1 2 3 4 5] 随机排列后的数组: [3 1 4 5 2] ``` ##### 示例 2:对指定范围内整数执行随机排列 对于给定的一个正整数n作为参数传递给此函数,它将创建并返回长度为n且由 `[0,..., n-1]` 组成的新数组,并对其进行随机重排: ```python permuted_range = np.random.permutation(10) print("随机排列后的范围:", permuted_range) ``` 这可能得到像这样的输出: ``` 随机排列后的范围: [4 2 8 1 9 0 7 3 5 6] ``` ##### 示例 3:处理二维或多维数组的情况 当应用于更高维度的数据结构时,仅会对最外层(即第一轴)上的子数组做重新排序操作而不影响内部数据布局: ```python matrix = np.arange(12).reshape((4, 3)) shuffled_matrix = np.random.permutation(matrix) print("原矩阵:\n", matrix) print("\n经过permutation之后的结果:\n", shuffled_matrix) ``` 这段程序可以产生类似以下形式的结果: ``` 原矩阵: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] 经过permutation之后的结果: [[ 6 7 8] [ 0 1 2] [ 9 10 11] [ 3 4 5]] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值