Skip to content

Commit a28c52b

Browse files
authored
Create 3704.Count-No-Zero-Pairs-That-Sum-to-N.cpp
1 parent 309590a commit a28c52b

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
using LL = long long;
2+
class Solution {
3+
LL memo[18][2][2][2];
4+
int L;
5+
vector<int>digits;
6+
public:
7+
LL dfs(int pos, int carry, int endA, int endB) {
8+
if (pos==L) {
9+
if (carry==0 && endA==1 && endB==1)
10+
return 1;
11+
else
12+
return 0;
13+
}
14+
15+
if (memo[pos][carry][endA][endB]!=-1)
16+
return memo[pos][carry][endA][endB];
17+
18+
LL ret = 0;
19+
int target = digits[pos];
20+
for (int i=0; i<=9; i++) {
21+
if(endA==1 && i!=0) continue;
22+
if(endA==0 && i==0) continue;
23+
vector<int>A;
24+
if (endA) A.push_back(1);
25+
else {
26+
A.push_back(0);
27+
if (i!=0) A.push_back(1);
28+
}
29+
30+
31+
for (int j=0; j<=9; j++) {
32+
if (endB==1 && j!=0) continue;
33+
if (endB==0 && j==0) continue;
34+
int sum = i+j+carry;
35+
if (sum%10!=target) continue;
36+
int ncarry = (sum>=10)?1:0;
37+
38+
vector<int>B;
39+
if (endB) B.push_back(1);
40+
else {
41+
B.push_back(0);
42+
if (j!=0) B.push_back(1);
43+
}
44+
45+
for (int nxt_enda: A)
46+
for (int nxt_endb: B)
47+
ret += dfs(pos+1, ncarry, nxt_enda, nxt_endb);
48+
}
49+
}
50+
51+
memo[pos][carry][endA][endB] = ret;
52+
return ret;
53+
54+
};
55+
56+
long long countNoZeroPairs(long long n) {
57+
58+
fill(&memo[0][0][0][0], &memo[0][0][0][0]+18*2*2*2, -1);
59+
60+
LL temp = n;
61+
while (temp>0) {
62+
digits.push_back(temp%10);
63+
temp/=10;
64+
}
65+
L = digits.size();
66+
67+
return dfs(0,0,0,0);
68+
}
69+
};

0 commit comments

Comments
 (0)