Skip to content

Instantly share code, notes, and snippets.

@mrandri19
Last active October 8, 2020 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrandri19/32e672dbd7f23701b6e470bb652f3a6c to your computer and use it in GitHub Desktop.
Save mrandri19/32e672dbd7f23701b6e470bb652f3a6c to your computer and use it in GitHub Desktop.
LeetCode Solutions
class Solution:
from functools import lru_cache
def getRow(self, rowIndex: int) -> List[int]:
# 1 0 0 0 0 0 j
# 1 1 0 0 0 0
# 1 2 1 0 0 0
# 1 3 3 1 0 0
# 1 4 6 4 1 0
# 1 5 10 10 5 1
# i
@lru_cache()
def row(i, j):
if i < 0 or j < 0: return 0
if i == 0 and j == 0: return 1
return row(i-1, j-1) + row(i-1, j)
return [row(rowIndex, i) for i in range(rowIndex+1)]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None: return head # len 0
if head.next == None: return head # len 1
old = None
cur = head
nxt = head.next
# NULL 1 -> 2 -> 3 -> 4 -> 5 -> NULL
# old cur next
# NULL <- 1 2 -> 3 -> 4 -> 5 -> NULL
# old cur next
# NULL <- 1 <- 2 3 -> 4 -> 5 -> NULL
# old cur next
while nxt != None:
cur.next = old
old, cur, nxt = cur, nxt, nxt.next
cur.next = old
return cur
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode, prev = None) -> ListNode:
# 1 -> 2 -> 3 -> 4 -> 5 -> NULL
# NULL 1 -> 2 -> 3 -> 4 -> 5 -> NULL
# prev head tmp
# NULL <- 1 2 -> 3 -> 4 -> 5 -> NULL
# NULL <- 1 <- 2 3 -> 4 -> 5 -> NULL
# NULL <- 1 <- 2 <- 3 4 -> 5 -> NULL
if head is None: return prev
tmp = head.next
head.next = prev
return self.reverseList(head = tmp, prev = head)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment