LeetCode 的硬币兑换问题超过了时间限制

我正在尝试解决LeetCode 上的Coin Change 问题:

http://img1.mukewang.com/610119390001cd2e06390469.jpg

我想出了我认为与解决方案中提到的自下而上的动态编程方法相同的方法:


import math



class Solution:

    def coinChange(self, coins, amount):

        fewest = [0] * (amount + 1)

        for i in range(1, amount + 1):

            fewest[i] = 1 + min(

                (fewest[i - coin] for coin in

                    [c for c in coins if i - c >= 0]),

                default=math.inf)

        return fewest[amount] if fewest[amount] < math.inf else -1

以下是pytest我用来验证解决方案的一些测试用例:


def test_1():

    assert Solution().coinChange([1, 2, 5], 1) == 1



def test_2():

    assert Solution().coinChange([1, 2, 5], 2) == 1



def test_3():

    assert Solution().coinChange([1, 2, 5], 3) == 2



def test_4():

    assert Solution().coinChange([1, 2, 5], 4) == 2



def test_5():

    assert Solution().coinChange([1, 2, 5], 5) == 1



def test_67():

    assert Solution().coinChange([1, 2, 5], 6) == 2

    assert Solution().coinChange([1, 2, 5], 7) == 2



def test_8():

    assert Solution().coinChange([1, 2, 5], 8) == 3



def test_11():

    assert Solution().coinChange([1, 2, 5], 11) == 3



def test_no_way():

    assert Solution().coinChange([2], 3) == -1

问题是我收到“超出时间限制”错误:

http://img1.mukewang.com/6101195e00017b0422421253.jpg

但是,如果我复制这个测试用例并在本地运行它,我发现该算法只需要0.02s:


import pytest


def test_time_limit_exceeded():

    Solution().coinChange(

        [205, 37, 253, 463, 441, 129, 156, 429, 101, 423, 311],

        6653)



if __name__ == "__main__":

    pytest.main([__file__, '--duration', '1'])

导致以下输出:


============================= test session starts ==============================

platform darwin -- Python 3.6.6, pytest-3.8.1, py-1.6.0, pluggy-0.7.1

rootdir: /Users/kurtpeek/GoogleDrive/CodeRust, inifile:

collected 11 items


coin_changing_leetcode2.py ...........                                   [100%]


=========================== slowest 1 test durations ===========================

0.02s call     coin_changing_leetcode2.py::test_time_limit_exceeded

========================== 11 passed in 0.07 seconds ===========================

知道为什么 LeetCode 无法实现此实现吗?


肥皂起泡泡
浏览 203回答 2
2回答

PIPIONE

似乎这件作品:&nbsp;&nbsp;fewest[i]&nbsp;=&nbsp;1&nbsp;+&nbsp;min( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(fewest[i&nbsp;-&nbsp;coin]&nbsp;for&nbsp;coin&nbsp;in &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[c&nbsp;for&nbsp;c&nbsp;in&nbsp;coins&nbsp;if&nbsp;i&nbsp;-&nbsp;c&nbsp;>=&nbsp;0]), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default=math.inf)检查所有硬币,过滤适当的硬币。但是您可以对硬币名义值进行排序,并且仅针对给定的 i 遍历足够小的名义值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python