Problem Solving with Go course

Recursion and DPCounting Combinations

Problem Solving with Go

Display

Theme

Recursion and DP · Test exercise

Counting Combinations

In the previous lesson, order mattered: 1+2 and 2+1 were two patterns. Often it doesn't: a crate holding a 2 kg box and a 3 kg box is the same crate whichever went in first. Counting combinations needs a recursion that can't produce the same set twice.

Decide one weight at a time

Line up the weights and make one decision at a time about the first weight still in play:

  • take no more of it, and move on to the next weight; or
  • take one more of it, and stay on the same weight (you may take another).
ways(i, left) = ways(i+1, left)               skip weights[i]
              + ways(i, left - weights[i])    one more weights[i]

Because each weight is decided before the next, a combination is always built in the same order, so it's counted exactly once. The base cases: left == 0 means the crate is exactly full, one way; running out of weights with left > 0 means zero ways.

For "at most one of each", the only change is the second line: after taking weights[i], move on to i+1.

A struct as the memo key

The answer now depends on two numbers, i and left. A map key can be any comparable type, so put both in a small struct:

type state struct {
	i, left int
}

memo := map[state]int{}

state{2, 15} and state{2, 15} are equal, so the second time the recursion asks the same question it finds the answer in the map. The number of different states is at most len(weights) × (total + 1), which is the most work the memoised recursion can do.

When the answer depends on more things (a position, a direction, keys collected so far), add them to the struct. Thinking "what exactly does the rest of the answer depend on?" is the heart of dynamic programming.

Task

This lesson's input gives the crate size and the box weights. The weights are all different and at least 1.

  1. Complete combos(weights []int, total int) int: how many ways boxes fill the crate to exactly total kg, with any number of boxes of each weight. Order doesn't matter.
  2. Complete combosEachOnce(weights []int, total int) int: the same, with at most one box of each weight.

An empty crate (total == 0) can be filled in exactly one way: no boxes. The tests use totals up to 1,000, so remember your answers.

main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// state is one question the recursion asks: in how many ways can the boxes from
// index i onwards make up exactly left kilograms?
type state struct {
	i, left int
}

// combos returns how many ways boxes of the given weights fill a crate of exactly total
// kilograms, using any number of boxes of each weight. Order doesn't matter: 2+3 and
// 3+2 are the same way. The weights are different and at least 1.
func combos(weights []int, total int) int {
	// TODO: skip weights[i], or take one more of it; remember answers in a map[state]int
	return 0
}

// combosEachOnce is combos with at most one box of each weight.
func combosEachOnce(weights []int, total int) int {
	// TODO
	return 0
}

func main() {
	total := 0
	var weights []int
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		f := strings.Fields(scanner.Text())
		if len(f) < 2 {
			continue
		}
		for _, s := range f[1:] {
			n, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println("bad number:", s)
				return
			}
			if f[0] == "crate" {
				total = n
			} else {
				weights = append(weights, n)
			}
		}
	}
	fmt.Printf("ways to fill %d kg with boxes of %v kg: %d\n", total, weights, combos(weights, total))
	fmt.Println("with at most one box of each weight:", combosEachOnce(weights, total))
}
Go runtime not loaded yet

2 lines · 28 B of the 1 MB limit. Submit always uses the lesson's own input.