1. 螺旋矩阵 II
给定一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
num = 1
left, right, top, bottom = 0, n - 1, 0, n - 1
while num <= n * n:
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
if top <= bottom:
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
return matrix
2. 排列序列
给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
- "123"
- "132"
- "213"
- "231"
- "312"
- "321"
给定 n 和 k,返回第 k 个排列。
import math
class Solution:
def getPermutation(self, n: int, k: int) -> str:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
nums = list(range(1, n + 1))
result = []
k -= 1
for i in range(n - 1, -1, -1):
fact = factorial(i)
index = k // fact
result.append(str(nums.pop(index)))
k %= fact
return ''.join(result)
标签:排列,matrix,int,Study,num,Algorithms,Part30,self,def
From: https://www.cnblogs.com/stephenxiong001/p/18415106