这段代码旨在获取一个整数硬币值数组、要进行的更改数量和一个用于收集答案的空数组,并且应该返回一组硬币,这些硬币可以产生正确的更改数量(假设问题是可能的)。
从 puts 语句看来,递归似乎表现良好并寻求正确答案,但返回的解决方案不是有效答案。有人可以让我知道我做错了什么吗?
我的代码:
def brute_solver(coins,amount,answer)
puts "Coins: #{coins}, Amount: #{amount}, Answer: #{answer}"
return answer.sort! if amount == 0
coins.each do |c|
brute_solver(coins, amount - c, answer.dup << c) unless amount - c < 0
end
end
运行 brute_solver 的示例尝试:
1.9.3p194 :001 > require './change_challenge.rb'
=> true
1.9.3p194 :002 > brute_solver([1,3,5],7,[])
Coins: [1, 3, 5], Amount: 7, Answer: []
Coins: [1, 3, 5], Amount: 6, Answer: [1]
Coins: [1, 3, 5], Amount: 5, Answer: [1, 1]
Coins: [1, 3, 5], Amount: 4, Answer: [1, 1, 1]
Coins: [1, 3, 5], Amount: 3, Answer: [1, 1, 1, 1]
Coins: [1, 3, 5], Amount: 2, Answer: [1, 1, 1, 1, 1]
Coins: [1, 3, 5], Amount: 1, Answer: [1, 1, 1, 1, 1, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 1, 1, 1, 1, 1, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 1, 1, 1, 3]
Coins: [1, 3, 5], Amount: 1, Answer: [1, 1, 1, 3]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 1, 1, 3, 1]
Coins: [1, 3, 5], Amount: 2, Answer: [1, 1, 3]
Coins: [1, 3, 5], Amount: 1, Answer: [1, 1, 3, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 1, 3, 1, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 1, 5]
Coins: [1, 3, 5], Amount: 3, Answer: [1, 3]
Coins: [1, 3, 5], Amount: 2, Answer: [1, 3, 1]
Coins: [1, 3, 5], Amount: 1, Answer: [1, 3, 1, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 3, 1, 1, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 3, 3]
Coins: [1, 3, 5], Amount: 1, Answer: [1, 5]
Coins: [1, 3, 5], Amount: 0, Answer: [1, 5, 1]
Coins: [1, 3, 5], Amount: 4, Answer: [3]
Coins: [1, 3, 5], Amount: 3, Answer: [3, 1]
Coins: [1, 3, 5], Amount: 2, Answer: [3, 1, 1]
Coins: [1, 3, 5], Amount: 1, Answer: [3, 1, 1, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [3, 1, 1, 1, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [3, 1, 3]
Coins: [1, 3, 5], Amount: 1, Answer: [3, 3]
Coins: [1, 3, 5], Amount: 0, Answer: [3, 3, 1]
Coins: [1, 3, 5], Amount: 2, Answer: [5]
Coins: [1, 3, 5], Amount: 1, Answer: [5, 1]
Coins: [1, 3, 5], Amount: 0, Answer: [5, 1, 1]
=> [1, 3, 5]