"""Brute Force用一條掃描線掃過sum的數字,記錄每個點會穿過多少brickidxes list 紀錄每個wall idx, wall_sum list 紀錄每個wall 當前的sumO(n*w) n is sum number, w in # of walls"""classSolution:defleastBricks(self,wall: List[List[int]]) ->int: n =len(wall) ans = n size =sum(wall[0]) wall_sum = [0] * n idxes = [0] * nfor num inrange(1, size):for i, w inenumerate(wall_sum):if w < num: wall_sum[i]+= wall[i][idxes[i]] idxes[i]+=1 count =0for w in wall_sum:if w > num: count +=1 ans =min(ans, count)return ans
"""HashMapUse HashMap 紀錄每個wall brick的right edge跟起始的距離,最後一個不用加上# of walls - right edge = # of 穿越數O(b) b is # of total bricks"""from collections import defaultdictclassSolution:defleastBricks(self,wall: List[List[int]]) ->int: n =len(wall) dic =defaultdict(int)for w in wall: sumUp =0for b in w[:-1]: sumUp+=b dic[sumUp]+=1 ans = nfor v in dic.values(): ans =min(ans, n-v)return ans
403. Frog Jump
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit. If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units
"""DFS with MemorizationT: O(n^3)S: O(n^2)"""defcanCross(self,stones: List[int]) ->bool: n =len(stones) dp = [[-1]*n for _ inrange(n)] return self.helper(0, 0, dp, stones)==1defhelper(self,idx,jump,dp,stones): n =len(stones)if idx == n-1:return1if dp[idx][jump] >=0:return dp[idx][jump]for i inrange(idx+1, n): gap = stones[i]- stones[idx]ifabs(jump - gap)<=1:if self.helper(i, gap, dp, stones)==1: dp[idx][gap] =1return1 dp[idx][jump] =0return0
"""DP用set紀錄jump過來的stepT: O(n^3)S: O(n^2)"""defcanCross(self,stones: List[int]) ->bool: d ={}for s in stones: d[s]=set() d[0].add(0)for s in stones:for k in d[s]:for step inrange(k-1, k+2):if step >0and (s + step) in d: d[s+step].add(step)returnlen(d[stones[-1]])!=0