發表文章

目前顯示的是 4月, 2017的文章

[LeetCode] 508. Most Frequent Subtree Sum

圖片
508. Most Frequent Subtree Sum Add to List Description Hints Submissions Solutions Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed  by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order. Examples 1 Input: 5 / \ 2 -3 return [2, -3, 4], since all the values happen only once, return all of them in any order. Examples 2 Input: 5 / \ 2 -5 return [2], since 2 happens twice, however -5 only occur once. Note:   You may assume the sum of values in any subtree is in the range of 32-bit signed integer. Subscribe   to see which companies asked this question.  找出子樹 加總 最高的 line 10 - 17: 深度優先左右子樹並加總 存到一個 字典叫 self.temp line 15 - 16: 處理 key error line 21 - 24: 找出最高的次數 line 25 - 28:...

[LeetCode] 198. House Robber

圖片
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and   it will automatically contact the police if two adjacent houses were broken into on the same night . Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight   without alerting the police . 有一排房子,小偷可以去偷 如果偷了第一間就不能偷第二間(不能偷相鄰的), 請問小偷的最大利益? 號稱最經典 最簡單的 動態規劃題目. 什麼是動態規劃?  https://www.youtube.com/watch?v=J3oLkc_TEVw 思路:  定義狀態 -> 轉移方程 -> 計算最優解並存下來 -> 由小到大推導結果 假設一排房子裡面的價值是 [2,1,1,1], 請問小偷的最大利益? 1. 定義狀態 設定 dp[3] 為小偷的最大利益 2.轉移方程 來看 dp[0] 是什麼意思, 如果只有一間房子 [2] 請問小偷的最大利益是多少? 很明顯 如果小偷 不偷那利益就是 0 偷了就是 2 所以當然是偷, 故 dp[0] = house[0] 再看 dp[1] 是什麼意思, 如果有兩間房子 [2,1] 請問小偷的最大利益是多少? 比一下就知道了 dp[1] = max (house[0], house[1]) 再看 dp[2] 應該...

[LeetCode] 46. Permutations & 47. Permutations II

圖片
Total Accepted:   154997 Total Submissions:   370049 Difficulty:   Medium Contributor:   LeetCode Given a collection of   distinct   numbers, return all possible permutations. For example, [1,2,3]   have the following permutations: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 找出數字的全部組合, 用dfs 搜尋  在dfs的時候 每次把自己的數值加到 path 裡 然後對剩下的nums 繼續做dfs. 一旦path長度等於nums的長度 就把path 加到res去  line 13: 傳入nums並且排除nums[i] , 記得要用深copy 傳path給下一個dfs   DFS 走的順序 nums:  [1, 2, 3] path:  [] res:   [] nums:  [2, 3] path:  [1] res:   [] nums:  [3] path:  [1, 2] res:   [] nums:  [] path:  [1, 2, 3] res:   [] nums:  [2] path:  [1, 3] res:   [[1, 2, 3]] nums:  [] path:  [1, 3, 2] res:   [[1, 2, 3]] nums:  [1, 3] path:  [2] res:  ...