Advertisement
norswap

Problem

Sep 27th, 2017
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4.  
  5. public final class Problem
  6. {
  7.     static class IntList
  8.     {
  9.         IntList (int i, IntList next) {
  10.             this.i = i;
  11.             this.next = next;
  12.         }
  13.  
  14.         public int i;
  15.         public IntList next;
  16.     }
  17.  
  18.     // works best if set sorted in increasing order
  19.     static void solutions (int target, int... set)
  20.     {
  21.         IntList remaining = null;
  22.         for (int i: set)
  23.             remaining = new IntList(i, remaining);
  24.  
  25.         List<IntList> solutions = solutions(target, 0, null, remaining);
  26.  
  27.         int i = 1;
  28.         for (IntList solution: solutions) {
  29.             System.out.print("solution " + i + ": ");
  30.             while (solution != null) {
  31.                 System.out.print(solution.i);
  32.                 if (solution.next != null) System.out.print(", ");
  33.                 solution = solution.next;
  34.             }
  35.             System.out.println();
  36.             ++i;
  37.         }
  38.     }
  39.  
  40.     static List<IntList> solutions (int target, int total, IntList selected, IntList remaining)
  41.     {
  42.         if (remaining == null)
  43.             return Collections.emptyList();
  44.  
  45.         List<IntList> solutions = new ArrayList<>();
  46.         int total2 = total + remaining.i;
  47.  
  48.         if (total2 == target)
  49.             // first item yield a solution
  50.             solutions.add(new IntList(remaining.i, selected));
  51.         else if (total2 < target)
  52.             // include first item
  53.             solutions.addAll(
  54.                 solutions(target, total2, new IntList(remaining.i, selected), remaining.next));
  55.  
  56.         // omit first item
  57.         solutions.addAll(solutions(target, total, selected, remaining.next));
  58.         return solutions;
  59.     }
  60.  
  61.     public static void main (String[] args)
  62.     {
  63.         solutions(7, 1, 2, 3, 4);
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement