2016年11月30日

花了差不多一下午补DP相关的东西,终于勉强做完了377. Combination Sum IV

在思路上绕了好久,最后还是没解决,忍不住去搜索了。然后发现是自己不擅长的DP,花了差不多整个下午,终于能勉强答题了。

class Solution(object):
    def combinationSum4(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        dp = [1] + [0] * target
        
        for i in range(target + 1):
            for num in nums:
                if i + num <= target:
                    dp[i + num] += dp[i]
        
        return dp[target]

答完题回来看看,似乎确实不难啊……

2016年11月17日

378. Kth Smallest Element in a Sorted Matrix的附带收获

神之多重list展开:

matrix_expanded = [element for line in matrix for element in line]

这很Python,写了两个for循环的我给跪了……

2016年11月9日

406. Queue Reconstruction by Height 的Python解法

研究了好久算法,最后参考了别人的思路,才发现代码可以这么简单……

思路总结:
1. 预排序,h从大到小,k从小到大
2. 依次把每个元素插到新list的k位置

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        result = []
        
        people.sort(key = operator.itemgetter(1))
        people.sort(key = operator.itemgetter(0), reverse = True)
        
        for p in people:
            result.insert(p[1], p)
            
        return result

这样的思路实现起来,真的很简单啊!