【LeetCode 964】 Least Operators to Express Number

给定一个正整数x,我们需要构造一个表达式,其中包含加、减、乘、除四种运算,使得该表达式的值等于目标值。遵循常规的运算顺序,不允许使用一元负号。目标是使用最少的运算符来构造这样的表达式。返回所需的运算符数量。该问题可以通过类似搜索的方法解决,考虑数字的二进制表示,寻找最小的运算符数量。

题目描述

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

思路

和race car 那道题类似。注意到,符号的添加就是对数字 进行 -x^i 的操作,最后要减到0,k = logx(t),有两种方式,可以先到 t 前面的数字,2^k, 或者 t后面的数字 2^(k+1)。
注意,2^k需要的符号是k,最后因为第一个一定可以是正的,省一个符号。

看了花花酱的题解,感觉更像是bfs。cost小的点先扩展。

代码

class Solution {
public:
    int leastOpsExpressTarget(int x, int target) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> que;
        unordered_set<int> s;
        que.emplace(0, target);
        
        while(!que.empty()) {
            int cost = que.top().first;
            int t = que.top().second;
            que.pop();
            
            if (t == 0) return cost-1;
            if (s.count(t)) continue;
            s.insert(t);
            
            int k = log(t) / log(x);
            int l = t - pow(x, k);
            que.emplace(cost+(k == 0 ? 2 : k), l);
            int r = pow(x, k+1) - t;
            que.emplace(cost+k+1, r);
        }
        
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值