import java.util.*; // More examples of recursive backtracking public class Backtracking2 { public static void main(String[] args) { List prices = new ArrayList<>(); prices.add(1); prices.add(2); prices.add(3); prices.add(5); waysToSpend(prices, 3); } // Prints out all the ways to spend the given dollarsLeft using the list // of item prices. Items can be purchased more than once, and the order // in which the purchases are made matters. public static void waysToSpend(List prices, int dollarsLeft) { waysToSpend(prices, dollarsLeft, new Stack<>()); } // Prints out all the ways to spend the given dollarsLeft using the list // of item prices, where chosen is the prefix of all the answers printed. private static void waysToSpend(List prices, int dollarsLeft, Stack chosen) { if (dollarsLeft == 0) { System.out.println(chosen); } else if (dollarsLeft > 0) { // prevent exploring a dead end! for (int price : prices) { chosen.push(price); // choose waysToSpend(prices, dollarsLeft - price, chosen); // explore chosen.pop(); // unchoose } } } }