leetcode 59. 插入区间 60. 排列序列
作者:互联网
leetcode 59. 插入区间 60. 排列序列
59. 螺旋矩阵 II
难度中等541收藏分享切换为英文接收动态反馈
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
通过次数140,965
提交次数179,683
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Author : mtl
# @Desc : ***
# @File : 59.py
# @Software: PyCharm
from typing import List
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
total = n * n
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
i = 0
matrix = [[False for _ in range(n)] for _ in range(n)]
num = 0
row, col = 0, 0
while i < total:
matrix[row][col] = i + 1
row, col = row + direction[num][0], col + direction[num][1]
if (row >= n or row < 0) or \
(col >= n or col < 0) or matrix[row][col] != False:
row, col = row - direction[num][0], col - direction[num][1]
num += 1
if num >= len(direction):
num = 0
row, col = row + direction[num][0], col + direction[num][1]
i += 1
return matrix
if __name__ == '__main__':
n = 4
print(Solution().generateMatrix(n))
60. 排列序列
难度困难603收藏分享切换为英文接收动态反馈
给出集合 [1,2,3,...,n]
,其所有元素共有 n!
种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3
时, 所有排列如下:
"123"
"132"
"213"
"231"
"312"
"321"
给定 n
和 k
,返回第 k
个排列。
示例 1:
输入:n = 3, k = 3
输出:"213"
示例 2:
输入:n = 4, k = 9
输出:"2314"
示例 3:
输入:n = 3, k = 1
输出:"123"
提示:
1 <= n <= 9
1 <= k <= n!
通过次数94,360
提交次数179,415
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Author : mtl
# @Desc : ***
# @File : 60.py
# @Software: PyCharm
class Solution:
def getPermutation(self, n: int, k: int) -> str:
nlist = [str(i+1) for i in range(n)]
result_list = []
valid = False
def dfs(nlist, n, alist):
nonlocal result_list, k, valid
if n <= 2:
result_list.append(alist + [nlist[0], nlist[1]])
result_list.append(alist + [nlist[1], nlist[0]])
if len(result_list) > k:
valid = True
return
for i in range(len(nlist)):
lnlist = nlist.copy()
alist.append(nlist.pop(i))
dfs(nlist, n - 1, alist)
if valid:
return
nlist = lnlist
alist.pop()
if n == 1:
return "1"
dfs(nlist, n, [])
return "".join(result_list[k - 1])
def getPermutation(self, n: int, k: int) -> str:
factorial = [1]
for i in range(1,n):
factorial.append(factorial[-1] * i)
a = [1] * (n + 1)
k -= 1
ans = ""
for i in range(1,n+1):
order = k // factorial[n - i] + 1
for j in range(1,n+1):
order -= a[j]
if order == 0:
ans += str(j)
a[j] = 0
break
k %= factorial[n - i]
return ans
if __name__ == '__main__':
n = 4
k = 9
a = [1,2,3]
b = [2,3]
# print(b.pop(1))
print(Solution().getPermutation(n, k))
[n - i]
return ans
if __name__ == '__main__':
n = 4
k = 9
a = [1,2,3]
b = [2,3]
# print(b.pop(1))
print(Solution().getPermutation(n, k))
标签:__,direction,59,leetcode,60,num,nlist,col,row 来源: https://blog.csdn.net/mtl1994/article/details/121797603