//记忆化递归 -> 记忆化动态规划,此时记录了所有的解 funcclimbStairs(_n: Int) -> Int { guard n >2else { return n } var res =Array(repeating: 0, count: n +1) res[1] =1 res[2] =2 for i in3... n { res[i] = res[i -1] + res[i -2] } return res[n] } //优化空间,只记录前两个解 funcclimbStairs(_n: Int) -> Int { guard n >2else { return n } var res =0 var pre_1 =1 var pre_2 =2 for_in3... n { res = pre_1 + pre_2 pre_1 = pre_2 pre_2 = res } return res }
funccoinChange(_coins: [Int], _amount: Int) -> Int { if amount ==0 { return0 } var res =Int.max for coin in coins { if amount - coin <0 { continue } let tmp = coinChange(coins, amount - coin) if tmp ==-1 { continue } res =min(res, tmp +1) } return res ==Int.max ?-1 : Int(res) }
记忆化递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funccoinChange(_coins: [Int], _amount: Int) -> Int { funchelp(_coins: [Int], _amount: Int, _memory: inout [Int]) -> Int { if amount ==0 { return0 } if memory[amount] !=-2 { return memory[amount] } var res =Int.max for coin in coins { if amount - coin <0 { continue } let tmp = help(coins, amount - coin, &memory) if tmp ==-1 { continue } res =min(res, tmp +1) } memory[amount] = res ==Int.max ?-1 : Int(res) return memory[amount] } var memory =Array(repeating: -2, count: amount +1) return help(coins, amount, &memory) }
动态规划
1 2 3 4 5 6 7 8 9 10 11 12 13
funccoinChange(_coins: [Int], _amount: Int) -> Int { if amount ==0 { return0 } var memory =Array(repeating: amount +1, count: amount +1) memory[0] =0 for i in1... amount { for coin in coins { if i - coin >=0 { memory[i] =min(memory[i], memory[i - coin] +1) } } } return memory[amount] > amount ?-1 : memory[amount] }