zoukankan      html  css  js  c++  java
  • 282. Expression Add Operators

    Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or * between the digits so they evaluate to the target value.

    Examples: 

    "123", 6 -> ["1+2+3", "1*2*3"] 
    "232", 8 -> ["2*3+2", "2+3*2"]
    "105", 5 -> ["1*0+5","10-5"]
    "00", 0 -> ["0+0", "0-0", "0*0"]
    "3456237490", 9191 -> []

     1 class Solution {
     2 public:
     3     vector<string> addOperators(string num, int target) {
     4 
     5         vector<string> res;
     6         if (num.size() == 0)
     7             return res;
     8 
     9         DFS(num, target, 0, "", res, 0, 0);
    10         return res;
    11     }
    12 
    13     void DFS(string& num, int& target, int cur, string path,
    14             vector<string>& res, long long diff, long long sum) {
    15 
    16         if (cur == int(num.size()) && sum == target) {
    17             res.push_back(path);
    18             return;
    19         }
    20         for (size_t i = cur; i < num.size(); i++) {
    21             string curStr = num.substr(cur, i - cur + 1);
    22             if (curStr.size() > 1 && curStr[0] == '0')
    23                 return;
    24             long  curVal = atol(curStr.c_str());
    25             if (cur > 0) {
    26                 DFS(num, target, i + 1, path + '+' + curStr, res, curVal,
    27                         sum + curVal);
    28                 DFS(num, target, i + 1, path + '-' + curStr, res, -curVal,
    29                         sum - curVal);
    30                 DFS(num, target, i + 1, path + '*' + curStr, res, diff * curVal,
    31                         sum - diff + diff * curVal);
    32             } else {
    33                 DFS(num, target, i + 1, path + curStr, res, curVal,
    34                         sum + curVal);
    35             }
    36         }
    37 
    38     }
    39 };
  • 相关阅读:
    生于忧患,死于安乐
    【网络流24题】骑士共存问题
    【网络流24题】最长不下降子序列问题
    【网络流24题】太空计划问题
    SG函数
    【网络流24题】餐巾计划问题
    【APIO2019】奇怪装置
    【HEOI2016/TJOI2016】游戏
    【SDOI2015】星际战争
    【CQOI2009】跳舞
  • 原文地址:https://www.cnblogs.com/wxquare/p/5073751.html
Copyright © 2011-2022 走看看