077_兑换零钱

知识点:贪心、动态规划、完全背包

LeetCode第三百二十二题:https://leetcode-cn.com/problems/coin-change/submissions/

语言:GoLang

// 贪心算法, 双百
func coinChange(coins []int, amount int) int {
    sort.Slice(coins, func(i, j int) bool {
		return coins[i] > coins[j]
	})

    ans := math.MaxInt64
    greedy(coins, amount, 0, 0, &ans)

    if ans == math.MaxInt64 {
        return -1
    }
    return ans
}
func greedy(coins []int, amount, count, index int, ans *int) {
    if amount == 0 {
        if *ans > count {
            *ans = count
        }
        return
    }

    if index == len(coins) {
        return
    }

    for k := amount / coins[index]; k >= 0 && count + k < *ans; k-- {
        greedy(coins, amount - k * coins[index], count + k, index + 1, ans)
    }
}



// 暴力解法dfs,超时。加个memo优化一下,时间也只有5%
var memo map[int]int
func coinChange_(coins []int, amount int) int {
    sort.Sort(sort.Reverse(sort.IntSlice(coins)))

    memo = map[int]int{}
    dfs(coins, amount)
    return memo[amount]
}

func dfs(coins []int, amount int) int {
    if v, ok := memo[amount]; ok {
		return v
	}

    if amount == 0 {
        return 0
    }
    if amount < 0 {
        return -1
    }

    memo[amount] = math.MaxInt64
    for _, v := range coins {
        count := dfs(coins, amount - v)
        if count == -1 {
            continue
        }

        if count + 1 < memo[amount] {
            memo[amount] = count + 1
        }
    }
    if memo[amount] == math.MaxInt64 {
        memo[amount] = -1
    }

    return memo[amount]
}
posted @ 2020-07-23 10:17  Cenyol  阅读(94)  评论(0编辑  收藏  举报