-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathFindThePunishmentNumberOfAnInteger.java
More file actions
99 lines (97 loc) · 2.53 KB
/
FindThePunishmentNumberOfAnInteger.java
File metadata and controls
99 lines (97 loc) · 2.53 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//plain recursion
class Solution {
public boolean isPartition(int j, String i2, int i, int curSum){
int n = i2.length();
// base case
if(j == n){
return (curSum == i);
}
for(int index=j;index<n;index++){
int val = Integer.parseInt(i2.substring(j,index+1));
if(isPartition(index+1,i2,i,curSum+val)){
return true;
}
}
return false;
}
public int punishmentNumber(int n) {
int res=0;
for(int i=1;i<=n;i++){
String i2 = Integer.toString(i*i);
if(isPartition(0,i2,i,0)){
res += (i*i);
}
}
return res;
}
}
//pruning
class Solution {
public boolean isPartition(int j, String i2, int i, int curSum){
int n = i2.length();
// base case
if(j == n){
return (curSum == i);
}
if(curSum > i){
return false;
}
for(int index=j;index<n;index++){
int val = Integer.parseInt(i2.substring(j,index+1));
if(isPartition(index+1,i2,i,curSum+val)){
return true;
}
}
return false;
}
public int punishmentNumber(int n) {
int res=0;
for(int i=1;i<=n;i++){
String i2 = Integer.toString(i*i);
if(isPartition(0,i2,i,0)){
res += (i*i);
}
}
return res;
}
}
//dp
class Solution {
public boolean isPartition(int j, String i2, int i, int curSum, int dp[][]){
int n = i2.length();
// base case
if(j == n){
return (curSum == i);
}
if(curSum > i){
return false;
}
if(dp[j][curSum]!=-1){
return (dp[j][curSum] == 1);
}
for(int index=j;index<n;index++){
int val = Integer.parseInt(i2.substring(j,index+1));
if(isPartition(index+1,i2,i,curSum+val,dp)){
dp[j][curSum] =1;
return true;
}
}
dp[j][curSum] =0;
return false;
}
public int punishmentNumber(int n) {
int res=0;
for(int i=1;i<=n;i++){
String i2 = Integer.toString(i*i);
int len = i2.length();
int dp[][] = new int[len][i+1];
for(int k=0;k<len;k++){
Arrays.fill(dp[k],-1);
}
if(isPartition(0,i2,i,0,dp)){
res += (i*i);
}
}
return res;
}
}