LC78 Subset

Backtracking class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: """tc O(N*2^N) sc O(N*2^N) """ res = [] size = len(nums) def dfs(start, path): res.append(path.copy()) # or path[:] for i in range(start, size): path.append(nums[i]) dfs(i+1, path) # if not using path.copy(), can do dfs(i+1, path + [nums[i]]) and remove pop operation... [Read More]

LC278 First Bad Version

class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ l = 1 r = n while l<r: mid = l + (r-l)//2 if isBadVersion(mid): r = mid else: l = mid+1 return l if isBadVersion(l) is True else None [Read More]

LC88 Pascal's Triangle II

class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # time O((m+n)lg(m+n)) space O(1) if not nums1 or not nums2: return nums1 + nums2 nums1[m:] = nums2[:n] nums1.sort() solution2: faster but more space class Solution:... [Read More]

LC83 Remove Duplicates from Sorted List

# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # time O(N) space O(1) def deleteDuplicates(self, head: ListNode) -> ListNode: if not head or not head.next: return head cur = head # (1)if current val is... [Read More]
Tags: LinkedList

LC77 Combinations

class Solution: def combine(self, n: int, k: int) -> List[List[int]]: self.res = [] # if n<=0 or k <=0 or k>n: # return res self._dfs(1,k,n,[]) return self.res def _dfs(self,start, k, n, pre): if len(pre) == k: self.res.append(pre[:]) return for i in range(start,n+1): pre.append(i) self._dfs(i+1,k,n,pre) pre.pop() # clear out pre stack... [Read More]
Tags: Backtracking