# 964. Least Operators to Express Number

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/least-operators-to-express-number/

> 内容描述

```
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.

When writing such an expression, we adhere to the following conventions:

The division operator (/) returns rational numbers.
There are no parentheses placed anywhere.
We use the usual order of operations: multiplication and division happens before addition and subtraction.
It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.

 

Example 1:

Input: x = 3, target = 19
Output: 5
Explanation: 3 * 3 + 3 * 3 + 3 / 3.  The expression contains 5 operations.
Example 2:

Input: x = 5, target = 501
Output: 8
Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.  The expression contains 8 operations.
Example 3:

Input: x = 100, target = 100000000
Output: 3
Explanation: 100 * 100 * 100 * 100.  The expression contains 3 operations.
 

Note:

2 <= x <= 100
1 <= target <= 2 * 10^8
```

## 解题方案

> 思路 1
******- 时间复杂度: O(lg(Target))******- 空间复杂度: O(1)******


参考[donggua_fu](https://leetcode.com/problems/least-operators-to-express-number/discuss/208445/c%2B%2B-recursive-easy-to-understand)

能AC， 但是beats 0%

```python
class Solution:
    def leastOpsExpressTarget(self, x, target):
        """
        :type x: int
        :type target: int
        :rtype: int
        """
        # At this time, you can get target either by add target times x/x or 
        # subtract (x - target) times x/x to x
        # For example, x = 3, target = 2. Then, 3/3 + 3/3 or 3 - 3/3 is possible result
        if x > target:
            return min(target * 2 - 1, (x - target) * 2)
        if x == target:  # just push x at the end
            return 0
        sums, times = x, 0
        while sums < target:  # this is gready, put as much as possible 'x'
            times += 1
            sums *= x
        if sums == target:  # one more 'x' you put, one more operator
            return times
        # when you have remainder, you have two choices, one is add, the other is subtract
        # for example, x = 3, target = 5. Then, 5 = 3 + 2 or 5 = 9 - 4
        l, r = sys.maxsize, sys.maxsize
        if sums - target < target:
            l = self.leastOpsExpressTarget(x, sums - target) + times  # using subtract
        r = self.leastOpsExpressTarget(x, target - (sums // x)) + times - 1  # using add
        return min(l, r) + 1  # No matter +/- used, one more operator is add
```



> 思路 2
******- 时间复杂度: O(lg(Target))******- 空间复杂度: O(lg(Target))******

加一下cache, 一行就够了```@functools.lru_cache(None)```

beats 66.67%

```python
import functools


class Solution:
    @functools.lru_cache(None)
    def leastOpsExpressTarget(self, x, target):
        """
        :type x: int
        :type target: int
        :rtype: int
        """
        # At this time, you can get target either by add target times x/x or 
        # subtract (x - target) times x/x to x
        # For example, x = 3, target = 2. Then, 3/3 + 3/3 or 3 - 3/3 is possible result
        if x > target:
            return min(target * 2 - 1, (x - target) * 2)
        if x == target:  # just push x at the end
            return 0
        sums, times = x, 0
        while sums < target:  # this is gready, put as much as possible 'x'
            times += 1
            sums *= x
        if sums == target:  # one more 'x' you put, one more operator
            return times
        # when you have remainder, you have two choices, one is add, the other is subtract
        # for example, x = 3, target = 5. Then, 5 = 3 + 2 or 5 = 9 - 4
        l, r = sys.maxsize, sys.maxsize
        if sums - target < target:
            l = self.leastOpsExpressTarget(x, sums - target) + times  # using subtract
        r = self.leastOpsExpressTarget(x, target - (sums // x)) + times - 1  # using add
        return min(l, r) + 1  # No matter +/- used, one more operator is add
```


> 思路 3
******- 时间复杂度: O(lg(Target))******- 空间复杂度: O(lg(Target))******

完全参考[solution](https://leetcode.com/problems/least-operators-to-express-number/solution/)的解法

beats 89.38%

```python
import functools
class Solution:
    def leastOpsExpressTarget(self, x, target):
        """
        :type x: int
        :type target: int
        :rtype: int
        """
        cost = list(range(28)) # log(target, x)最大为26.57, 因此我们可能需要幂为27
        cost[0] = 2 # x^0 = 1 = +x/x, 需要2个操作符

        @functools.lru_cache(None)
        def dp(power, target): # 当前幂次为power，要达到target
            if target == 0: return 0
            if target == 1: return cost[power]
            if power >= 27: return float('inf')

            t, r = divmod(target, x)
            return min(r * cost[power] + dp(power+1, t),
                       (x-r) * cost[power] + dp(power+1, t+1))

        return dp(0, target) - 1 # we have to remove the leading operator just like +x/x
```






























































