leetcode 964. Least Operators to Express Number

本文探讨了如何使用最少的操作符(加、减、乘、除)将单个正整数通过数学表达式转换为目标值的问题。文章提供了一种算法,通过递归地减少目标值与基数的差距,直到找到最优解,即达到目标所需的最少操作数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1op2, 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:

  1. The division operator (/) returns rational numbers.
  2. There are no parentheses placed anywhere.
  3. We use the usual order of operations: multiplication and division happens before addition and subtraction.
  4. 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

解题思路:

从题意中可以知道其实target就是以x为进制的数,所以就是求 target = \sum ai*x^{i} ;

所以从高位开始算;

class Solution {
public:
    int leastOpsExpressTarget(int x, int target) 
    {
        set<pair<int , int>> q ;//
        unordered_set<int> seen ;
        q.emplace(0 , target) ;
        while(!q.empty())
        {
            auto it = begin(q) ;
            int c = it->first , t = it->second ;
            q.erase(it) ;
            if(t == 0) return c - 1 ;
            if(seen.count(t)) continue ;
            seen.insert(t) ;
            int n = log(t) / log(x) , t1 = t - pow(x , n) , t2 = pow(x , n + 1) - t ;
            if(!seen.count(t1))
            {
                q.emplace(c + (n == 0 ? 2 : n) , t1) ;
            }
            if(!seen.count(t2))
            {
                q.emplace(c + n + 1 , t2) ;
            }
        }
        
        return -1 ;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值