282. 給表達式添加運算符

282. 給表達式添加運算符

給定一個僅包含數字 0-9 的字符串 num 和一個目標值整數 target ,在 num 的數字之間添加 二元 運算符(不是一元)+、- 或 * ,返回所有能夠得到目標值的表達式。

示例 1:輸入: num = "123", target = 6
輸出: ["1+2+3", "1*2*3"] 示例 2:輸入: num = "232", target = 8
輸出: ["2*3+2", "2+3*2"]示例 3:輸入: num = "105", target = 5
輸出: ["1*0+5","10-5"]示例 4:輸入: num = "00", target = 0
輸出: ["0+0", "0-0", "0*0"]示例 5:輸入: num = "3456237490", target = 9191
輸出: []

解題思路

  1. 使用遞歸的方法,生成所有可能產生的表達式
  2. 利用基本計算器的代碼,計算出所有表達式的值,找出滿足題意的表達式

代碼

class Solution {List<String> res=new ArrayList<>();int t;public List<String> addOperators(String num, int target) {t=target;int c=0;for (int i=0;i<num.length()-1;i++){c=(c*10)+num.charAt(i)-'0';operator(num,i+1,""+c);if (i==0&&num.charAt(i)=='0')break;}if(num.equals(""+target))res.add(num);return res;}    public long calculate(String s) {Stack<Long> stack=new Stack<>();Stack<Long> characterStack=new Stack<>();int n=s.length();int i = 0,sign=1,cur=0;while ( i < n) {char c = s.charAt(i);if(c==' '){i++;continue;}if(Character.isDigit(c)){long sum=0;while (i < n&&Character.isDigit(s.charAt(i))){sum*=10;sum+=s.charAt(i)-'0';i++;}stack.push(sum);i--;}else {if(c=='+'||c=='-'){if(!characterStack.isEmpty()){stack.push(stack.pop()*characterStack.pop()+stack.pop());}characterStack.push(c=='+'?1L:-1L);}else{int sum=0;i++;while (s.charAt(i)==' ') i++;while (i < n&&Character.isDigit(s.charAt(i))){sum*=10;sum+=s.charAt(i)-'0';i++;}if(c=='*')stack.push(stack.pop()*sum);elsestack.push(stack.pop()/sum);i--;}}i++;}return  stack.size()==1?stack.pop():stack.pop()*characterStack.pop()+stack.pop();}public void operator(String num, int s,String sb) {if (s==num.length()){if (calculate(sb)==t)res.add(sb);return;}int c=0;for (int i=s;i<num.length();i++){c=(c*10)+num.charAt(i)-'0';operator(num,i+1,sb+"+"+c);operator(num,i+1,sb+"-"+c);operator(num,i+1,sb+"*"+c);if (i==s&&num.charAt(i)=='0')break;}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/389973.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389973.shtml
英文地址,請注明出處:http://en.pswp.cn/news/389973.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java 在底圖上繪制線條_使用底圖和geonamescache繪制k表示聚類

java 在底圖上繪制線條This is the third of four stories that aim to address the issue of identifying disease outbreaks by extracting news headlines from popular news sources.這是四個故事中的第三個&#xff0c;旨在通過從流行新聞來源中提取新聞頭條來解決識別疾病…

python selenium處理JS只讀(12306)

12306為例 js "document.getElementById(train_date).removeAttribute(readonly);" driver.execute_script(js)time2獲取當前時間tomorrow_time 獲取明天時間 from selenium import webdriver import time import datetime time1datetime.datetime.now().strftime(&…

Mac上使用Jenv管理多個JDK版本

使用Java時會接觸到不同的版本。大多數時候我在使用Java 8&#xff0c;但是因為某些框架或是工具的要求&#xff0c;這時不得不讓Java 7上前線。一般情況下是配置JAVA_HOME&#xff0c;指定不同的Java版本&#xff0c;但是這需要人為手動的輸入。如果又要選擇其他版本&#xff…

交互式和非交互式_發布交互式劇情

交互式和非交互式Python中的Visual EDA (Visual EDA in Python) I like to learn about different tools and technologies that are available to accomplish a task. When I decided to explore data regarding COVID-19 (Coronavirus), I knew that I would want the abilit…

5886. 如果相鄰兩個顏色均相同則刪除當前顏色

5886. 如果相鄰兩個顏色均相同則刪除當前顏色 總共有 n 個顏色片段排成一列&#xff0c;每個顏色片段要么是 ‘A’ 要么是 ‘B’ 。給你一個長度為 n 的字符串 colors &#xff0c;其中 colors[i] 表示第 i 個顏色片段的顏色。 Alice 和 Bob 在玩一個游戲&#xff0c;他們 輪…

Sunisoft.IrisSkin.SkinEngine 設置winform皮膚

Sunisoft.IrisSkin.SkinEngine se; se new Sunisoft.IrisSkin.SkinEngine { SkinAllForm true, SkinFile "..\..\skin\EmeraldColor2.ssk" };Sunisoft.IrisSkin.SkinEngine skin new Sunisoft.IrisSkin.SkinEngine(); //具體樣式文件 地址&#xff0c;可以自行修…

docker 相關操作

docker-compose down //關閉所有容器 docker-compose up //開啟所有容器docker-compose restart //重啟所有容器單獨更新某個容器時用腳本$ docker ps // 查看所有正在運行容器 $ docker stop containerId // containerId 是容器的ID$ docker ps -a // 查看所有容器 $…

電子表格轉換成數據庫_創建數據庫,將電子表格轉換為關系數據庫,第1部分...

電子表格轉換成數據庫Part 1: Creating an Entity Relational Diagram (ERD)第1部分&#xff1a;創建實體關系圖(ERD) A Relational Database Management System (RDMS) is a program that allows us to create, update, and manage a relational database. Structured Query …

【Vue.js學習】生命周期及數據綁定

一、生命后期 官網的圖片說明&#xff1a; Vue的生命周期總結 var app new Vue({el:"#app", beforeCreate: function(){console.log(1-beforeCreate 初始化之前);//加載loading},created: function(){console.log(2-created 創建完成);//關閉loading},be…

5885. 使每位學生都有座位的最少移動次數

5885. 使每位學生都有座位的最少移動次數 一個房間里有 n 個座位和 n 名學生&#xff0c;房間用一個數軸表示。給你一個長度為 n 的數組 seats &#xff0c;其中 seats[i] 是第 i 個座位的位置。同時給你一個長度為 n 的數組 students &#xff0c;其中 students[j] 是第 j 位…

Springboot(2.0.0.RELEASE)+spark(2.1.0)框架整合到jar包成功發布(原創)!!!

一、前言 首先說明一下&#xff0c;這個框架的整合可能對大神來說十分容易&#xff0c;但是對我來說十分不易&#xff0c;踩了不少坑。雖然整合的時間不長&#xff0c;但是值得來紀念下&#xff01;&#xff01;&#xff01;我個人開發工具比較喜歡IDEA&#xff0c;創建的sprin…

求一個張量的梯度_張量流中離散策略梯度的最小工作示例2 0

求一個張量的梯度Training discrete actor networks with TensorFlow 2.0 is easy once you know how to do it, but also rather different from implementations in TensorFlow 1.0. As the 2.0 version was only released in September 2019, most examples that circulate …

docker環境 快速使用elasticsearch-head插件

docker環境 快速使用elasticsearch-head插件 #elasticsearch配置 #進入elk容器 docker exec -it elk /bin/bash #head插件訪問配置 echo #head插件訪問# http.cors.enabled: true http.cors.allow-origin: "*" >>/etc/elasticsearch/elasticsearch.yml#重啟el…

476. 數字的補數

476. 數字的補數 給你一個 正 整數 num &#xff0c;輸出它的補數。補數是對該數的二進制表示取反。 例 1&#xff1a;輸入&#xff1a;num 5 輸出&#xff1a;2 解釋&#xff1a;5 的二進制表示為 101&#xff08;沒有前導零位&#xff09;&#xff0c;其補數為 010。所以你…

zabbix網絡發現主機

1 功能介紹 默認情況下&#xff0c;當我在主機上安裝agent&#xff0c;然后要在server上手動添加主機并連接到模板&#xff0c;加入一個主機組。 如果有很多主機&#xff0c;并且經常變動&#xff0c;手動操作就很麻煩。 網絡發現就是主機上安裝了agent&#xff0c;然后server自…

python股市_如何使用python和破折號創建儀表板來主導股市

python股市始終關注大局 (Keep Your Eyes on the Big Picture) I’ve been fascinated with the stock market since I was a little kid. There is certainly no shortage of data to analyze, and if you find an edge you can make some easy money. To stay on top of the …

阿里巴巴開源 Sentinel,進一步完善 Dubbo 生態

為什么80%的碼農都做不了架構師&#xff1f;>>> 阿里巴巴開源 Sentinel&#xff0c;進一步完善 Dubbo 生態 Sentinel 開源地址&#xff1a;https://github.com/alibaba/Sentinel 轉載于:https://my.oschina.net/dyyweb/blog/1925839

數據結構與算法 —— 鏈表linked list(01)

鏈表(維基百科) 鏈表&#xff08;Linked list&#xff09;是一種常見的基礎數據結構&#xff0c;是一種線性表&#xff0c;但是并不會按線性的順序存儲數據&#xff0c;而是在每一個節點里存到下一個節點的指針(Pointer)。由于不必須按順序存儲&#xff0c;鏈表在插入的時候可以…

離群值如何處理_有理處理離群值的局限性

離群值如何處理ARIMA models can be quite adept when it comes to modelling the overall trend of a series along with seasonal patterns.ARIMA模型可以很好地建模一系列總體趨勢以及季節性模式。 In a previous article titled SARIMA: Forecasting Seasonal Data with P…

網絡爬蟲基礎練習

0.可以新建一個用于練習的html文件&#xff0c;在瀏覽器中打開。 1.利用requests.get(url)獲取網頁頁面的html文件 import requests newsurlhttp://news.gzcc.cn/html/xiaoyuanxinwen/ res requests.get(newsurl) #返回response對象 res.encodingutf-8 2.利用BeautifulSoup的H…