LeetCode 964 - Least Operators to Express Number


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 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
https://github.com/cherryljr/LeetCode/blob/master/Least%20Operators%20to%20Express%20Number.java
 * Approach: DP (Express Target Number in Base X)
 * 这道题目考察的是对 进制 方面的掌握和理解。但是在此基础上有进行了一个的升级,使得难度有所提高了。
 * 题目给出了一个 base number: x.需要我们通过对 x 进行四则运算最后得到 target.
 * 但是运算过程中不能有 括号。这点非常重要,因为这就以为着 除法 的用处只有一个:
 *  用来产生 1.除此之外其没有任何用处(因为题目要求的是使用最少的运算符)
 *  eg. x^2 = x * x = x * x * x / x
 *  毫无以为此时引入除法只会增加操作符的使用,带来负面影响
 * 那么根据以上条件,可以有如下表示:
 *  target = c0*x^0 + c1*x^1 + c2*x^2 + c3*x^3 + ... + cn*x^n,   -x < c < x
 * 因此最后我们需要求的结果就是:
 *  ops = 2*|c0| + 1*|c1| + 2*|c2| + 3*|c3| + ... + n*|cn| - 1
 * 这里注意到我们进行了一次 -1 操作。
 * 这是因为,我们以上所有的操作都是带符号进行运算的。
 * 但是表达式第一项的符号是可以省略掉的。可能有人会有疑问:负号的话就不能省略了。
 * 然而根据题目的数据范围可知:x 与 target 均为 正整数。
 * 因此表达式中必定至少存在一项正的,所以我们可以把 负的这一项 移到后面去,这样就能省略掉一个操作符了。
 * 同时,对于第一项,我们这里 *2,这是因为要产生一个 1,或者是 -1.我们都需要两个操作符。(±x/x)
 *
 * 此外,我们还需要知道非常重要的一点就是:
 *  target 可以由比较小的数叠加而来,而可以由比较大的数减去一个值得到。
 * 而我们需要求的就是最短的路径(最少需要多少个操作符)。
 * 因此这里实际上是一个 DP 问题,即我们只关心由 x 经过运算得到某一个值 n 最少需要的操作符个数。
 * 但是并不关心中间的具体操作过程(无后效性问题)。
 *  eg. x = 3, target = 7
 *  target = 3*3 - 3/3 - 3/3, ops = 5
 *  target = 3 + 3 + 3/3 , ops = 3
 *  (注意:7的三进制是 21)即:7 = 2*3^1 + 1 * 3^0, 对于 ops = 2 * 1 + 2 - 1 = 3
X. https://leetcode.com/problems/least-operators-to-express-number/discuss/208428/Java-DFS-with-memoization
Inspired by the race car problem. Only need to consider two candidates. But unfortunately I cannot give mathematical prove of the correntness.
    Map<Integer, Integer> memo = new HashMap<>();
    public int leastOpsExpressTarget(int x, int target) {
        if (target == 1) 
            return x == 1 ? 0 : 1;
        if (memo.containsKey(target))
            return memo.get(target);
        long product = x;
        int count = 0;
        while (product < target) {
            count++;
            product *= x;
            
        }
        
        // candidate1 : in the form : x*x*...*x - (......) = target
        int cand1 = Integer.MAX_VALUE;
        if (product == target)
            cand1 = count;
        else if (product - target < target)
            cand1 = count + leastOpsExpressTarget(x, (int)(product - target)) + 1;
        
        // candidate2 : in the form : x*x*...*x + (......) = target
        int cand2 = Integer.MAX_VALUE;
        product /= x;
        cand2 = leastOpsExpressTarget(x, (int)(target - product)) + (count == 0 ? 2 : count);
        int res = Math.min(cand1, cand2);
        memo.put(target, res);
        return res;
    }
X. DFS + cache
Time complexity: O(x * log(t)/log(x))
Space complexity: O(x * log(t)/log(x))
  int leastOpsExpressTarget(int x, int target) {
    return dp(x, target);
  }
private:
  unordered_map<int, int> m_;
  int dp(int x, int t) {
    if (t == 0) return 0;
    if (t < x) return min(2 * t - 1, 2 * (x - t));
    if (m_.count(t)) return m_.at(t);
    int k = log(t) / log(x);
    long p = pow(x, k);
    if (t == p) return m_[t] = k - 1;
    int ans = dp(x, t - p) + k; // t - p < t
    long left = p * x - t;
    if (left < t) // only rely on smaller sub-problems
      ans = min(ans, dp(x, left) + k + 1);
    return m_[t] = ans;
  }
https://leetcode.com/problems/least-operators-to-express-number/discuss/208475/Java-DFS-with-memo
  Map<String, Integer> memo;
  int x;

  public int leastOpsExpressTarget(int x, int target) {
    memo = new HashMap();
    this.x = x;
    return dp(0, target) - 1;
  }

  public int dp(int i, int target) {
    String code = "" + i + "#" + target;
    if (memo.containsKey(code))
      return memo.get(code);

    int ans;
    if (target == 0) {
      ans = 0;
    } else if (target == 1) {
      ans = cost(i);
    } else if (i >= 39) {
      ans = target + 1;
    } else {
      int t = target / x;
      int r = target % x;
      ans = Math.min(r * cost(i) + dp(i + 1, t), (x - r) * cost(i) + dp(i + 1, t + 1));
    }

    memo.put(code, ans);
    return ans;
  }

  public int cost(int x) {
    return x > 0 ? x : 2;

  }

https://zhanghuimeng.github.io/post/leetcode-964-least-operators-to-express-number/
这道题在本质上非常类似于进制表示:
target=a0+a1x+a2x2+
但是很大的一个区别在于,它对系数(理论上)没有限制,也因此对x的最大幂次没有限制(因为系数可以是负的)。而且我们的目标是最小化代价。容易推断出,生成一个x的幂次的代价为(包含前面的+/-运算符):
cost(xe)={2e=0ee1
显然,如果要生成一个aexe,最优的选择是都采用+或者都采用-运算符(因为同时用显然是浪费)。
因此整体的代价可以表示为
cost=2abs(a0)+2abs(a1)+3abs(a2)+
不妨首先把target表示成普通的x进制的形式:
target=b0+b1x+b2x2++bnxn,,0bi<x
可以认为ai是在bi的基础上得到的,例如:
target=(b0x+x2)+(b1+1)x+(b21)x2+
这个式子看起来好像借位,不过比实际中的借位要自由,因为现实的进制中不会出现b0这一位向b2借位的情况。
此时有a0=b0x+x2,,a1=b1+1,,a2=b21。显然此时整体的代价也变化了:
cost=2b0+2b1+3b2+
cost=2|b0x+x2|+2|b1+1|+3|b21|+
显然我们希望整体代价最小。考虑到x>=2,显然可以得出这样一个结论:从比前一位更往前的位借位是不值得的,而且一定是借一个负位。原因很简单:假定bibj借了k位(ji+2),则这两位的cost之和从|bi|(i+1)+|bj|(j+1)变成了|bi+kxji|(i+1)+|bjk|(j+1)。通过各种分类讨论可以发现,这个cost不可能减小。(懒得去讨论了……)
所以可以用递推的方法来考虑这个问题:令
f[i][0]=mincost(a0+a1x+a2x2++aixi)f[i][1]=mincost(a0+a1x+a2x2++(aix)xi)
也就是说f[i][1]是借了一个负位之后最小可能的表示的代价。则
f[i+1][0]=mincost(a0+a1x+a2x2++aixi+ai+1xi+1)=mincost(a0+a1x+a2x2++aixi)+cost(ai+1xi+1),cost(a0+a1x+a2x2++(aix)xi)+cost((ai+1+1)xi+1)=minf[i][0]+ai+1(i+1),f[i][1]+(ai+1+1)(i+1)
同理:
f[i+1][1]=minf[i][0]+|a[i+1]x|(i+1),f[i][1]+|a[i+1]x+1|(i+1)
然后就可以递推了,时间复杂度为O(log(N))
从借位的想法translate到递推还是不太容易啊……
以及,考虑到有借位的可能,需要递推到f[n],而不是f[n-1]
    int leastOpsExpressTarget(int x, int target) {
        int a[1000], n = 0;
        memset(a, 0, sizeof(a));
        int t = target;
        while (t > 0) {
            a[n++] = t % x;
            t /= x;
        }
        int f[1000][2];
        f[0][0] = 2 * a[0];
        f[0][1] = 2 * abs(a[0] - x);
        for (int i = 1; i <= n; i++) {
            f[i][0] = min(f[i-1][0] + a[i] * i, f[i-1][1] + (a[i] + 1) * i);
            f[i][1] = min(f[i-1][0] + abs(a[i] - x) * i, f[i-1][1] + abs(a[i] - x + 1) * i);
        }
        return f[n][0] - 1;
    }
X.
https://zxi.mytechroad.com/blog/uncategorized/leetcode-964-least-operators-to-express-number/
Dijkstra
Find the shortest path from target to 0 using ops.
Time complexity: O(nlogn)
Space complexity: O(nlogn) 
n = x * log(t) / log(x)
    int leastOpsExpressTarget(int x, int target) {
      priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
      unordered_set<int> s;
      q.emplace(0, target);
      while (!q.empty()) {
        const int c = q.top().first;
        const int t = q.top().second;
        q.pop();
        if (t == 0) return c - 1;
        if (s.count(t)) continue;
        s.insert(t);
        int n = log(t) / log(x);
        int l = t - pow(x, n);        
        q.emplace(c + (n == 0 ? 2 : n), l);
        int r = pow(x, n + 1) - t;        
        q.emplace(c + n + 1, r);
      }
      return -1;
    }



Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts