Looking for combinations that add up to 15 in a card of hands
I am writing a program that deals with c开发者_开发问答ards and a hand. A hand has 5 cards. I want to know whats a good algorithm for deciding which combination of cards add up to 15. Kings, Queens, Jacks, count as 10 and a Ace count as one.
This is very similar to subset sums, which I recently answered here: Subset Sum algorithm
The only tweak you need to make is to keep track of which card was used to get from possible[i]
to possible[i+n]
. You can keep track of these using a second array let's call it card_used
and then set card_used[i+n]
to a reference/index of the card used to get from i
to i+n
. Then at the end, you can retrieve the list of cards used to get to the sum of 15 (assuming possible[15]
is true) by backtracking through the list card_used
.
1) get the hand
2) loop thru the hand
2a) each iteration, add the value of the car to a running total.
2b) if you ever get to more than 15 you can exit this iteration
精彩评论