Computing target number from numbers in a set

后端 未结 7 582
太阳男子
太阳男子 2020-12-13 15:14

I\'m working on a homework problem that asks me this:

Tiven a finite set of numbers, and a target number, find if the set can be used to calculate the target number

7条回答
  •  温柔的废话
    2020-12-13 15:23

    Well, you didn't mention efficiency so I'm going to post a really brute force solution and let you optimize it if you want to. Since you can have parantheses, it's easy to brute force it using Reverse Polish Notation:

    First of all, if your set has n numbers, you must use exactly n - 1 operators. So your solution will be given by a sequence of 2n - 1 symbols from {{your given set}, {*, /, +, -}}

    st = a stack of length 2n - 1
    n = numbers in your set
    a = your set, to which you add *, /, +, -
    v[i] = 1 if the NUMBER i has been used before, 0 otherwise
    
    void go(int k)
    {
      if ( k > 2n - 1 ) 
      {
        // eval st as described on Wikipedia. 
        // Careful though, it might not be valid, so you'll have to check that it is   
        // if it evals to your target value great, you can build your target from the given numbers. Otherwise, go on.
    
        return;
      }
    
      for ( each symbol x in a )
        if ( x isn't a number or x is a number but v[x] isn't 1 )
        {
          st[k] = x;
          if ( x is a number )
            v[x] = 1;
    
          go(k + 1);
        }
    }
    

提交回复
热议问题