-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplitNumberProblem.java
More file actions
173 lines (75 loc) · 1.87 KB
/
SplitNumberProblem.java
File metadata and controls
173 lines (75 loc) · 1.87 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
public class SplitNumberProblem{
public static int splitNum(int num){
int[] arr=new int[num];
for (int i=0; i<arr.length;i++ ) {
arr[i] = i+1;
}
return process(arr,num,0,"");
}
public static int process(int[] arr,int rest,int index,String path){
if(rest == 0){
//System.out.println(path);
return 1;
}
int ways=0;
for (int ci = index; ci<arr.length&&rest - arr[ci]>=0; ci++) {
ways += process(arr,rest-arr[ci],ci,path+arr[ci]+",");
}
return ways;
}
public static int splitNum2(int num){
int[] arr=new int[num];
for (int i=0; i<arr.length;i++ ) {
arr[i] = i+1;
}
int[][] dp = new int[num+1][num+1];
for (int i=0; i<=num; i++) {
for (int j=0; j<=num; j++) {
dp[i][j]=-1;
}
}
return process2(arr,num,0,"",dp);
}
public static int process2(int[] arr,int rest,int index,String path,int[][] dp){
if(dp[rest][index]!=-1){
return dp[rest][index];
}
if(rest == 0){
//System.out.println(path);
return 1;
}
int ways=0;
for (int ci = index; ci<arr.length&&rest - arr[ci]>=0; ci++) {
ways += process2(arr,rest-arr[ci],ci,path+arr[ci]+",",dp);
}
dp[rest][index] = ways;
return ways;
}
public static int splitNum3(int num){
return process3(1,num,"");
}
public static int process3(int pre,int rest,String path){
if(rest == 0){
//System.out.println(path);
return 1;
}
if(pre > rest){
return 0;
}
if(rest == pre){
//System.out.println(path);
return 1;
}
int ways=0;
for (int first = pre; first<=rest; first++) {
ways += process3(first,rest-first,path+first+",");
}
return ways;
}
public static void main(String[] args){
int num = 70;
//System.out.println("C = "+splitNum(num));
System.out.println("C = "+splitNum2(num));
System.out.println("C = "+splitNum3(num));
}
}