Showing Posts From

Leetcode

LeetCode 72. Edit Distance

LeetCode 72. Edit Distance题目:给定两个单词,将第一个单词转换成第二个单词,需要的最少的步数。其中:替换,删除,增加都算是一个步数。思路:不知道为啥这题标为难,其实也是超级简单的题目,唯一需要动一点脑子的,就是删除的那个操作,第二个单词的下标是不需要往前移的。比较值得注意的一点是,如果用的元组来做dict的key,效率很低,有可能会超时,改为二维数组效率就会快很多了。 `class Solution: def __init__(self): self.cache = [] def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ self.cache = [[0] * len(word2) for i in range(len(word1))] return self.dp(word1, word2, 0, 0) def dp(self, word1, word2, i, j): if i == len(word1) or j == len(word2): return len(word1[i:]) + len(word2[j:]) elif self.cache[i][j] != 0: return self.cache[i][j] elif word1[i] == word2[j]: return self.dp(word1, word2, i + 1, j + 1) else: self.cache[i][j] = min(self.dp(word1, word2, i, j + 1) + 1, self.dp(word1, word2, i + 1, j) + 1, self.dp(word1, word2, i + 1, j + 1) + 1) return self.cache[i][j] `

LeetCode 712. Minimum ASCII Delete Sum for Two Strings

712. Minimum ASCII Delete Sum for Two Strings 又是dp题目题目:删掉两个字符串中的字符让两个字符串相同,并统计删掉的字符的ascii码总和,要求总和最低。思路:也是动态规划,和最长公共子序列很像,是个变种。 有两种思路,第一种:继续按照最长公共子序列来做,算出了最长公共子序列之后,拿两个字符串的ascii码总和减去公共子序列的ascii码值,就是去掉的字符串的ascii码的和;第二种:反向算最长公共子序列,当dp计算的时候,如果字符不相等,进行ascii码的计算,相等则继续循环。 我采用的是第二种思路,用的递归写法,个人认为递归的写法比较简单,一下就能开写,不太需要思考。 `class Solution: def __init__(self): self.cache = [] def minimumDeleteSum(self, s1, s2): """ :type s1: str :type s2: str :rtype: int """ self.cache = [[0] * (len(s2) + 1) for i in range(len(s1) + 1)] return self.dp(s1, s2, 0, 0) def dp(self, s1, s2, i, j): if i == len(s1) or j == len(s2): return self.cal(s1[i:]) + self.cal(s2[j:]) elif s1[i] == s2[j]: return self.dp(s1, s2, i + 1, j + 1) elif self.cache[i][j] != 0: return self.cache[i][j] else: self.cache[i][j] = min(self.dp(s1, s2, i, j + 1) + ord(s2[j]), self.dp(s1, s2, i + 1, j) + ord(s1[i])) return self.cache[i][j] return self.cache[(i, j)] def cal(self, string): rsum = 0 for i in string: rsum += ord(i) return rsum `

LeetCode 198&213. House Robber & House Robber II

LeetCode 198&213. House Robber & House Robber II 两题一起题目:抢劫房屋,不能抢劫相邻的房屋,否则会被抓。升级版的房屋是一个环,也就是最后和最先的房屋是相邻的。思路:基础版是最简单的动态规划,升级版就是抢最后一间和不抢最后一间的情况取最大的那个。只放基础版的代码了。 `class Solution: def rob(self, nums): """ :type nums: List[int] :rtype: int """ take = 0 not_take = 0 for i,n in enumerate(nums): index = i + 2 temp = take take = max(take, not_take + n) not_take = max(not_take, temp) return take `

LeetCode 746. Min Cost Climbing Stairs

LeetCode 746. Min Cost Climbing Stairs题目:爬楼梯,可以选择爬一级或者两级,每一级需要消耗的能量存储在cost数组中,可以选择从第一级或者第二级开始爬,求最小的能量消耗是多少。思路: 非常简单的一道动归题目,只需要用到缓存,就能直接解决了。唯一我用到的一个技巧:因为要爬到最上面,意味着要爬过最后一级台阶,那么我向数组里push一个消耗为0的台阶,作为最终目标。没有多想,直接开码: `/** * @param {number[]} cost * @return {number} */ var minCostClimbingStairs = function(cost) { cost.push(0); let target = cost.length - 1, memo = {}; if (target < 2) { return Math.min(...cost); } let r = function (i) { if (memo[i]) return memo[i]; if (i > 1) { memo[i] = Math.min(r(i - 1) + cost[i], r(i - 2) + cost[i]); } else { memo[i] = cost[i]; } return memo[i]; }; return r(target); }; `

LeetCode 10. Regular Expression Matching

题目:实现正则表达式的.和*两个符号。思路:第一时间看到正则,马上就想到了用while来不停匹配。后来遇到了a*a匹配aa,发现要处理贪心和不贪心多种情况,所以将while转为了递归。 题目考察的多是递归的设计和考虑多种情况是否周全,代码很少(JS实现): var isMatch = function(s, p) { if (!p) return !s; let match = !!s && (s[0] === p[0] || p[0] === "."); // console.log(s, p, match) if (p[1] === "*") { return isMatch(s, p.substr(2)) || (match && isMatch(s.substr(1), p)); } else { return match && isMatch(s.substr(1), p.substr(1)) } };如果觉得递归代码不好看,可以将递归改为动态规划,使用bottom-up或者简单的memo来提高程序的性能。

LeetCode 650. 2 Keys Keyboard

题目:初始化字符只有一个A,现在有两种操作:1.复制当前所有字符。2.粘贴。使用这两种操作得到n个A字符,求最少的步数。思路:我是在dp的tag下找到的这个题目,但是我发现最简单的解法应该直接使用贪心算法就可以了。 要得到n个A字符,可以认为最少的步数肯定是通过粘贴最多的字符来得到的,那么反推就能得到最少步数了。 举个例子,如果输入n=12,那么根据贪心的思想,可以认为是先得到6个A,然后进行复制粘贴两步得到,6个A又是通过3个A粘贴得到,3个A需要3步得到,那么总共需要的最少步数是:3(3A) + 2(3A -> 6A)+ 2(6A -> 12A)= 7步。 代码如下(JS实现): var minSteps = function(n) { let sum = 0; while (n >= 2) { for (let i = 2; i <= n; i++) { if (n % i === 0) { sum += i; n = n / i; break; } } } return sum; };&nbsp;

LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee

题目:给定一个股票价格数组prices,标记了每天股票的价格,还有一个股票买卖手续费fee。求交易最大利润。 比如: Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 Output: 8思路:动态规划,使用两个变量分别记录当前购买股票hold和售出股票cash获得的利润。 cash计算很简单,当前股票卖出的时候只要是赚的,就可以出售,递推式也就是: cash = Math.max(cash, hold + prices[i] - fee)hold的要求很简单,不要买亏就好了,那么递推式就是: hold = Math.max(hold, cash - prices[i])不知道这么说是否直观,可以根据例子来推算一下: 第一天的假设我们买了,cash = 0, hold = -1 第二天会发现,卖出股票减去手续费,没有赚,并且换一支持股,也更亏,那么第二天可以略过。 第三天同第二天。 第四天,很重要的一天。卖出股票减去手续费可以赚5块,那么直接卖。然后再买股票,那么持有股票的金额就为1元。 第五天,最后一天。卖出股票减去手续费可以赚7块,也卖掉。最后手中持有的钱就为8块了。 最后代码如下,JS实现: var maxProfit = function(prices, fee) { let hold = -prices[0], cash = 0; for (let i = 1; i < prices.length; i++) { cash = Math.max(cash, hold + prices[i] - fee); hold = Math.max(hold, cash - prices[i]); } return cash; };&nbsp;