Datawhale LeetCode腾讯精选练习50题 Task06

043 字符串相乘

题号:43
难度:中等
链接:https://leetcode-cn.com/problems/multiply-strings/

思路:
题目要求不能直接将输入转换为整数来处理,那么可以模拟作乘法时草稿纸上竖式乘法的计算过程。注意进位和稿纸上错位时是乘10的几次方。

python代码:

class Solution:
    def multiply(self, num1: str, num2: str) -> str:

        if num1 == "0" or num2 == "0":
            return "0"

        ans = 0
        count1 = len(num1)
        count2 = len(num2)
        for i in range(count2-1,-1,-1):
            temp1,temp2,cout = 0,0,0
            for j in range(count1-1,-1,-1):
                temp1 = (int(num2[i]) * int(num1[j]) + cout) % 10
                cout = (int(num2[i]) * int(num1[j]) + cout) // 10
                if(j == 0):
                    temp2 = temp1 * 10**(count1-1-j) + temp2 + cout*10**(count1-j)
                else:
                    temp2 = temp1 * 10**(count1-1-j) + temp2 
            ans = ans + temp2 * 10**(count2-1-i) 
        output = str(ans)
        return output

046 全排列

题号:46
难度:中等
链接:https://leetcode-cn.com/problems/permutations/

这个代码时官方题解的。我自己还没敲出来,先记录下来。希望整个打卡任务结束了可以一天一题重新整理思路和笔记。

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        def backtrack(first = 0):
            # 所有数都填完了
            if first == n:  
                res.append(nums[:])
            for i in range(first, n):
                # 动态维护数组
                nums[first], nums[i] = nums[i], nums[first]
                # 继续递归填下一个数
                backtrack(first + 1)
                # 撤销操作
                nums[first], nums[i] = nums[i], nums[first]
        
        n = len(nums)
        res = []
        backtrack()
        return res

链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/

053 最大子序和

题号:53
难度:简单
https://leetcode-cn.com/problems/maximum-subarray/

思路:
动态规划算法,用一个变量记录前面序列的和,当和是负数,抛弃前面的和值,和更新为当前指向的数值,当和是整数,则加到序列当前值,同时更新序列和进行后续计算。

class Solution:
    def maxSubArray(self, nums) -> int:
        count = len(nums)
        previous = 0
        for i in range (count):
            if previous > 0:
                nums[i] = nums[i] + previous
            previous = nums[i]
        return max(nums)

你可能感兴趣的:(DataWhale组队学习,Leetcode,50题,leetcode)