7.28笔记(第147场周赛前两道)

今天第二次参加周赛,能做出两道题很开心了,还记得第一次参加周赛时一道没写出来尴尬,继续加油。

5139. 第 N 个泰波那契数(很简单,递归会超时)

class Solution(object):
    def tribonacci(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = [0] * (n+1)
        if n == 0:
            return 0   
        if n == 1 or n == 2:
            return 1
        res[0] = 0
        res[1] = 1
        res[2] = 1
        for i in range(3,len(res)):
            res[i] = res[i-1] + res[i-2] + res[i-3]
        return res[-1]
        

5140. 字母板上的路径(写的很麻烦,由于第5行只有z元素,单独判断的,所以代码段有重复)

class Solution(object):
    def alphabetBoardPath(self, target):
        """
        :type target: str
        :rtype: str
        """
        res =''
        a = [0,0]
        for s in range(len(target)):
            r = (ord(target[s])-97)//5
            j = ((ord(target[s])-97) % 5)
            print(r,j)
            k = r - a[0]
            h = j - a[1]
            print(k,h)
            if a[0] == 5:
                if k == 0 and h == 0:
                    res += '!'
                    continue
                if k > 0:
                    for i in range(k):
                        res += 'D'
                elif k < 0:
                    for i in range(abs(k)):
                        res += 'U'
                if h > 0:
                    for i in range(h):
                        res += 'R'
                elif h < 0:
                    for i in range(abs(h)):
                        res += 'L'
                res += '!'
                a = [r,j]
                continue
            if k == 0 and h == 0:
                res += '!'
                continue
            if h > 0:
                for i in range(h):
                    res += 'R'
            elif h < 0:
                for i in range(abs(h)):
                    res += 'L'
            if k > 0:
                for i in range(k):
                    res += 'D'
            elif k < 0:
                for i in range(abs(k)):
                    res += 'U'
            res += '!'
            a = [r,j]
        return res
            

 

上一篇:AtCoder Beginner Contest 147


下一篇:LeetCode 147:Insertion Sort List