Guest User

Untitled

a guest
Jan 19th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. const DENOMINATIONS : [usize; 15] = [500_00, 200_00, 100_00, 50_00, 20_00, 10_00, 5_00, 2_00, 1_00, 50, 20, 10, 5, 2, 1];
  2.  
  3. fn num_combinations(sum: usize) -> u128 {
  4. let mut cache = vec![[None; 15]; sum+1];
  5. num_combinations_inner(sum, 0, &mut *cache)
  6. }
  7.  
  8. fn num_combinations_inner(sum: usize, min_index: usize, cache: &mut[[Option<u128>; 15]]) -> u128 {
  9. if let Some(res) = cache[sum][min_index] {
  10. // cache hit
  11. res
  12. } else {
  13. // cache miss
  14. let res = DENOMINATIONS[min_index..]
  15. .into_iter()
  16. .enumerate()
  17. .map(|(i, &d)| {
  18. if sum > d {
  19. // not there yet, so we recurse,
  20. // making sure not to use any denominations larger than d
  21. // (via min_index)
  22. num_combinations_inner(sum - d, min_index + i, cache)
  23. } else if sum == d {
  24. // exact fit
  25. 1
  26. } else {
  27. // too much
  28. 0
  29. }
  30. })
  31. .sum();
  32. // update cache
  33. cache[sum][min_index] = Some(res);
  34. res
  35. }
  36. }
  37.  
  38. fn main() {
  39. println!("{}", num_combinations(1_000_00));
  40. }
Add Comment
Please, Sign In to add comment