GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/cpp/282_Expression_Add_Operators.cpp at master · Alex220284/leetcode

Expand file tree

/

282_Expression_Add_Operators.cpp

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
53 lines (47 loc) · 1.77 KB
/

282_Expression_Add_Operators.cpp

Copy path

File metadata and controls

53 lines (47 loc) · 1.77 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> result;
if (num.size() == 0) return result;
findSolution(num, target, result, "", 0, 0, 0, ' ');
return result;
}
//DFS algorithm
void findSolution(const string &num, const int target,
vector<string>& result,
string solution,
int idx,
long long val,
long long prev,
char preop )
{
if (target == val && idx == num.size()){
result.push_back(solution);
return;
}
if (idx == num.size()) return;
string n;
long long v=0;
for(int i=idx; i<num.size(); i++) {
//get rid of the number which start by "0"
//e.g. "05" is not the case.
if (n=="0") return;
n = n + num[i];
v = v*10 + num[i]-'0';
if (solution.size()==0){
findSolution(num, target, result, n, i+1, v, 0, ' ');
}else{
// '+' or '-' needn't to adjust the priority
findSolution(num, target, result, solution + '+' + n, i+1, val+v, v, '+');
findSolution(num, target, result, solution + '-' + n, i+1, val-v, v, '-');
if (preop=='+') {
findSolution(num, target, result, solution + '*' + n, i+1, (val-prev)+prev*v, prev*v, preop);
}else if (preop=='-'){
findSolution(num, target, result, solution + '*' + n, i+1, (val+prev)-prev*v, prev*v, preop);
}else {
findSolution(num, target, result, solution + '*' + n, i+1, val*v, v, '*');
}
}
}
}
};
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.