# @lc app=leetcode.cn id=70 lang=python3
#
# [70] 爬楼梯
#
# @lc code=start
class Solution:
def climbStairs(self, n: int) -> int:
dp=[0 for i in range(n)]
for i in range(n):
if i == 0:
dp[0]=1
continue
if i == 1:
dp[1]=2
continue
dp[i]=dp[i-1]+dp[i-2]
return dp[n-1]
# @lc app=leetcode.cn id=64 lang=python3
#
# [64] 最小路径和
#
#动态规划 dp[i][j]时到i,j的最小路径和
# @lc code=start
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
row = len(grid)
col = len(grid[0])
dp=[[0]*col for i in range(row)]
for i in range(row):
for j in range(col):
if i == 0 and j!=0:
dp[i][j]=dp[i][j-1]+grid[i][j]
elif j == 0 and i!=0:
dp[i][j]=dp[i-1][j]+grid[i][j]
elif i==0 and j==0:
dp[i][j]=grid[0][0]
else :
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j]
return dp[row-1][col-1]
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
if m == 1 and n == 1:
if obstacleGrid[0][0] == 1: return 0
else: return 1
dp = [[0] * n for _ in range(m)]
for i in range(m):
if obstacleGrid[i][0] == 1: break
dp[i][0] = 1
for j in range(n):
if obstacleGrid[0][j] == 1: break
dp[0][j] = 1
for i in range(1, m):
for j in range(1, n):
if obstacleGrid[i][j] == 1:
dp[i][j] = 0
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
# @lc app=leetcode.cn id=61 lang=python3
#
# [61] 旋转链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
def lenlink(head):
i=0
while head != None:
head=head.next
i=i+1
return i
lens=lenlink(head)
if lens==0:
return head
k=k%(lens)
newlist=ListNode(0,None)
newcur=newlist
cur1 = head
cur2 = head
for i in range(lens-k):
cur1=cur1.next
#print(cur1.val)
for i in range(lens):
if i < k:
newcur.val= cur1.val
print(newcur.val)
cur1=cur1.next
newcur.next=ListNode(0,None)
newcur=newcur.next
else:
newcur.val= cur2.val
#print(cur2.val)
cur2=cur2.next
if i<lens-1:
newcur.next=ListNode(0,None)
newcur=newcur.next
return newlist
# @lc app=leetcode.cn id=60 lang=python3
#
# [60] 排列序列
#
# @lc code=start
class Solution:
def getPermutation(self, n: int, k: int) -> str:
nums=[i for i in range(1,n+1)]
def subgetPermutation(N,k,nums,str1):
import math
#print(k)
while 1:
if k<0 or len(nums)==1:
str1=str1+str(nums[0])
return str1
x=math.factorial(N-1)
for i in range(1,len(nums)+1):
if i*x>=k:
k=k-(i-1)*x if k-(i-1)*x>0 else k
N=N-1
#print(i,k,N,nums)
str1=str1+str(nums[i-1])
#print(str1)
nums.remove(nums[i-1])
#print(nums)
break
return subgetPermutation(n,k,nums,"")
# @lc code=end