Find and print num of solutions to x1+x2+x3=num

Devy :

I need to write a recusive function that recive an integer num and returns the number of solutions to the equation :x1 + x2 + x3 = num, where x1,x2,x3 are numbers between 1-10, the method should print all solutions.

For example if num=3 then the method will print 1+1+1 and will return 1.

if num=5 the method will return 6 and will print:

1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1

if num<3 or num>30 the method will return 0.

The method should be recursive without using loops. Global variables are not allowed. Lists are also not allowed.

Here my code, it works fine but it also prints duplicates, for num=5 it prints:

3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3

Here is my code:

public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num) 
{

    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;       
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }           
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}

How do I get the desired output without duplicates?

that other guy :

The reason why you're getting duplicates is that both solutions(1,2,1) and solutions(2,1,1) will lead you to 2 + 2 + 1.

The trivial way of not getting duplicate for three digits is count up from 111 to 10,10,10 as if it was a decimal integer:

private static int solutions(int num, int x1, int x2, int x3)
{
  if (x1 > 10 || x1 > num)
    return 0;
  if (x2 > 10 || x1+x2 > num)
    return solutions(num, x1+1, 1, 1);
  if (x3 > 10 || x1+x2+x3 > num)
    return solutions(num, x1, x2+1, 1);

  int me = 0;
  if (x1+x2+x3 == num) {
    System.out.printf("%d + %d + %d\n", x1, x2, x3);
    me=1;
  }
  return me + solutions(num, x1, x2, x3+1);
}

This mimics your approach of searching through the full space with pruning, but a more efficient solution could just search through x1 and x2 and set x3=num-x1-x2.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=95118&siteId=1