classSolution(object): deffindLengthOfLCIS(self, nums): ifnot nums: return0 maximum = 1 current = 1 for i in range(1, len(nums)): if nums[i - 1] < nums[i]: current += 1 else: maximum = max(maximum, current) current = 1 maximum = max(maximum, current) return maximum
defsearch(self, word): for m in self.magic: modify = 0 if len(m) == len(word): for i in range(len(m)): if m[i] != word[i]: modify += 1 if modify == 1: returnTrue returnFalse
Input: [ [2,3,4], [0,0,5], [8,7,6]] Output: 6 Explanation: You started from the point (0,0) and you can cut off the tree in (0,0) directly without walking.
### 方法 ### 我先將所有非0或1的數加入一個陣列中,將其排序後由小至大取出,利用BFS計算從目前位置到各點的最短距離,取出目前位置到欲修剪的距離。 很不幸的我的方法吃了一發 TLE ,應該是做的 BFS 有太多多餘的範圍了,應該只要找出目前位置到目的地的最短距離就好,之後若有時間再想辦法補上新的方法吧。
classSolution(object): defcutOffTree(self, forest): import math self.forest = forest self.r, self.c = len(self.forest), len(self.forest[0]) f = [col for row in forest for col in row if col != 0and col != 1] f.sort(reverse=True) total_step = 0 cur_pos = (0, 0) while f: self.num_step = [[math.inf for j in range(self.c)] for i in range(self.r)] self.num_step[cur_pos[0]][cur_pos[1]] = 0 self.min_step(cur_pos) next_cut = f.pop() next_pos = self.find_pos(next_cut) ifnot self.num_step[next_pos[0]][next_pos[1]] < math.inf: return-1 total_step += self.num_step[next_pos[0]][next_pos[1]] cur_pos = next_pos
deffind_pos(self, num): for i in range(len(self.forest)): if num in self.forest[i]: return (i, self.forest[i].index(num)) return-1
第4題 673. Number of Longest Increasing Subsequence
問題
給一個未排序的整數陣列,找出最長的遞增子序列的數量。
輸入與輸出
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.