LeetCode //C - 282. Expression Add Operators

282. Expression Add Operators

Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators ‘+’, ‘-’, and/or ‘*’ between the digits of num so that the resultant expression evaluates to the target value.

Note that operands in the returned expressions should not contain leading zeros.
 

Example 1:

Input: num = “123”, target = 6
Output: [“123”,“1+2+3”]
Explanation: Both “123” and “1+2+3” evaluate to 6.

Example 2:

Input: num = “232”, target = 8
Output: [“23+2","2+32”]
Explanation: Both “23+2" and "2+32” evaluate to 8.

Example 3:

Input: num = “3456237490”, target = 9191
Output: []
Explanation: There are no expressions that can be created from “3456237490” to evaluate to 9191.

Constraints:
  • 1 <= num.length <= 10
  • num consists of only digits.
  • − 2 31 < = t a r g e t < = 2 31 − 1 -2^{31} <= target <= 2^{31} - 1 231<=target<=2311

From: LeetCode
Link: 282. Expression Add Operators


Solution:

Ideas:
  1. Backtracking Function: The backtrack function generates all possible expressions by inserting operators at each position between the digits. It evaluates each expression to see if it matches the target.
  2. Handling Leading Zeros: The code ensures that numbers with leading zeros are skipped.
  3. Operators Handling: For each possible insertion of an operator (+, -, *), the expression is updated and the backtracking function is called recursively.
  4. Result Collection: Valid expressions that match the target are added to the result list.
Code:
#define MAX_LEN 1000

// Helper function to append the new expression to the result
void addResult(char ***result, int *returnSize, char *expr) {
    *result = realloc(*result, (*returnSize + 1) * sizeof(char *));
    (*result)[*returnSize] = strdup(expr);
    (*returnSize)++;
}

// Helper function for the backtracking process
void backtrack(char *num, int target, int pos, long currValue, long prevValue, char *expr, int len, char ***result, int *returnSize) {
    int numLen = strlen(num);

    // Base case: if we have processed all digits
    if (pos == numLen) {
        if (currValue == target) {
            expr[len] = '\0';
            addResult(result, returnSize, expr);
        }
        return;
    }

    for (int i = pos; i < numLen; i++) {
        // Skip numbers with leading zeros
        if (i != pos && num[pos] == '0') break;

        char currStr[i - pos + 2];
        strncpy(currStr, num + pos, i - pos + 1);
        currStr[i - pos + 1] = '\0';

        long currNum = atol(currStr);

        if (pos == 0) {
            // For the first number, we just append it to the expression
            strncpy(expr + len, currStr, i - pos + 1);
            backtrack(num, target, i + 1, currNum, currNum, expr, len + i - pos + 1, result, returnSize);
        } else {
            // Append '+' operator
            expr[len] = '+';
            strncpy(expr + len + 1, currStr, i - pos + 1);
            backtrack(num, target, i + 1, currValue + currNum, currNum, expr, len + i - pos + 2, result, returnSize);

            // Append '-' operator
            expr[len] = '-';
            strncpy(expr + len + 1, currStr, i - pos + 1);
            backtrack(num, target, i + 1, currValue - currNum, -currNum, expr, len + i - pos + 2, result, returnSize);

            // Append '*' operator
            expr[len] = '*';
            strncpy(expr + len + 1, currStr, i - pos + 1);
            backtrack(num, target, i + 1, currValue - prevValue + prevValue * currNum, prevValue * currNum, expr, len + i - pos + 2, result, returnSize);
        }
    }
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** addOperators(char* num, int target, int* returnSize) {
    char **result = NULL;
    *returnSize = 0;

    if (num == NULL || strlen(num) == 0) {
        return result;
    }

    char expr[MAX_LEN];
    backtrack(num, target, 0, 0, 0, expr, 0, &result, returnSize);

    return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值