【leetcode】403. Frog Jump

题目如下:

 

解题思路:我的做法是建立一个字典dic,key为stone,value是一个set,里面存的是从前面的所有stone跳跃到当前stone的unit集合。例如stones=[0,1,2,3]。stone3可以从stone1跳跃两步得到或者从stone2跳跃1步得到,所有dic[3] = (2,1)。那么从stone3可以跳的unit就是[1,2,3] (set中每个元素+1或者-1得到),通过stone3就能到达stone4,stone5,stone6。这样只要按顺序遍历stones,最后判断len(dic[stones[-1]]是否大于0即可。

代码如下:

class Solution(object):
    def canCross(self, stones):
        """
        :type stones: List[int]
        :rtype: bool
        """
        dic = {}
        for i in stones:
            dic[i] = set()
        dic[0].add(1)
        for i in stones:
            for j in dic[i]:
                if j+i in dic:
                    dic[j+i].add(j)
                if i != 0 and j+i+1 in dic:
                    dic[j+i+1].add(j+1)
                if  j-1 > 0 and j + i - 1 in dic:
                    dic[j + i - 1].add(j - 1)
        #print dic
        return len(dic[stones[-1]]) > 0

猜你喜欢

转载自www.cnblogs.com/seyjs/p/9177565.html