login
欢迎访问QkqBeer博客园!

BFS广度优先搜索算法(leetcode 322 python)

题目

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1

示例 1:

输入: coins = [1, 2, 5], amount = 11
输出: 3 
解释: 11 = 5 + 5 + 1

示例 2:

输入: coins = [2], amount = 3
输出: -1

class Solution(object):
    def coinChange(self, coins, amount):
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        if amount == 0:
            return 0
        value1 = []
        value2 = [0]
        nc = 0
        visited = [False] * (amount + 1)
        visited[0] = True
        while value2:
            nc += 1
            for v in value2:
                for c in coins:
                    newValue = v + c
                    if newValue == amount:
                        return nc
                    elif newValue > amount:
                        continue
                    elif not visited[newValue]:
                        visited[newValue] = True
                        value1.append(newValue)
            value1, value2 = [], value1
        return -1
                

  

 

posted @ 2019-01-09 10:22  BeerQkq  阅读(360)  评论(0编辑  收藏  举报