[LeetCode] Expression Add Operators

來源:互聯網
上載者:User

標籤:

This post shares a very nice solution, which is rewritten below.

 1 class Solution { 2 public: 3     vector<string> addOperators(string num, int target) { 4         int n = num.length(); 5         if (!n) return {}; 6         vector<string> ans; 7         for (int i = 1; i <= n; i++) { 8             string s = num.substr(0, i); 9             long v = stol(s);10             if (s != to_string(v)) continue;11             add(ans, num, target, s, i, v, v, ‘$‘);12         }13         return ans;14     }15 private:16     void add(vector<string>& ans, string& num, int target, string s, int i, long v, long pv, char op) {17         int n = num.length();18         if (i == n && v == target)19             ans.push_back(s);20         else {21             for (int p = i + 1; p <= n; p++) {22                 string t = num.substr(i, p - i);23                 long d = stol(t);24                 if (t != to_string(d)) continue;25                 add(ans, num, target, s + ‘+‘ + t, p, v + d, d, ‘+‘);26                 add(ans, num, target, s + ‘-‘ + t, p, v - d, d, ‘-‘);27                 add(ans, num, target, s + ‘*‘ + t, p, (op == ‘+‘) ? v - pv + pv * d : ((op == ‘-‘) ? v + pv - pv * d: pv * d), pv * d, op);28             }29         }30     }31 };

 

[LeetCode] Expression Add Operators

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.