zoukankan      html  css  js  c++  java
  • Leetcode: 1449. Form Largest Integer With Digits That Add up to Target

    Description

    Given an array of integers cost and an integer target. Return the maximum integer you can paint under the following rules:
    
    The cost of painting a digit (i+1) is given by cost[i] (0 indexed).
    The total cost used must be equal to target.
    Integer does not have digits 0.
    Since the answer may be too large, return it as string.
    
    If there is no way to paint any integer given the condition, return "0".
    

    Example

    Input: cost = [6,10,15,40,40,40,40,40,40], target = 47
    Output: "32211"
    

    Note

    cost.length == 9
    1 <= cost[i] <= 5000
    1 <= target <= 5000
    

    分析

    code

    第一次提交就 AC 的代码, 
    Runtime: 292 ms, faster than 60.00% of Python online submissions for Form Largest Integer With Digits That Add up to Target.
    Memory Usage: 25.1 MB, less than 39.85% of Python online submissions for Form Largest Integer With Digits That Add up to Target.
    
    class Solution(object):
        def largestNumber(self, costs, target):
            """
            :type cost: List[int]
            :type target: int
            :rtype: str
            """
            
            def mmax(a, b):
                if len(a) > len(b):
                    return a
                elif len(b) > len(a):
                    return b
                return max(a, b)
    
            helper = {}
            for i, v in enumerate(costs):
                helper[v] = str(i+1)
    
            dp = ['0' for _ in range(target+1)]
    
            for k in helper:
                try:
                    dp[k] = helper[k]
                except:
                    continue
    
            r = []
            for i in range (2, min(10, target+1)):
                for j in helper:
                    if j >= i or dp[i-j] == '0':
                        continue
                    r.append(i)
                    dp[i] = mmax(dp[i], max(dp[i-j], dp[j]) + min(dp[i-j], dp[j]))
    
            for i in r:
                helper.pop(i, 0)
    
            for i in range(10, target+1):
                for j in helper:
                    if j >= i or dp[i-j] == '0':
                        continue
                    dp[i] = mmax(dp[i], max(dp[j]+dp[i-j], dp[i-j]+dp[j]))
            return dp[-1]
    

    总结

    • 比较简单的 dp ,不应该归类为 hard 级别的 dp
  • 相关阅读:
    Horovod 分布式深度学习框架相关
    COO 与 CSR 稀疏矩阵存取格式;
    CUDA 编程相关;tensorflow GPU 编程;关键知识点记录;CUDA 编译过程;NVCC
    tensorflow dataloader 相关内容
    z390 m.2 接口插上sata 硬盘后,机械硬盘不识别;HDD 硬盘不识别;z390 m.2和 SATA 硬盘安装组合;
    C 实战练习题目10
    C 实战练习题目9
    C 实战练习题目8
    C 实战练习题目7
    C 实战练习题目6
  • 原文地址:https://www.cnblogs.com/tmortred/p/13235218.html
Copyright © 2011-2022 走看看