Implement intPartitions method

This commit is contained in:
2026-04-22 22:43:25 +03:30
parent c59b80f87c
commit 3e85586939
+58 -2
View File
@@ -1,3 +1,5 @@
import java.util.ArrayList;
public class MainExercises public class MainExercises
{ {
/* /*
@@ -145,8 +147,62 @@ public class MainExercises
*/ */
public int[][] intPartitions(int n) { public int[][] intPartitions(int n) {
// todo
return null; ArrayList<int[]> result = new ArrayList<>();
int[] current = new int[n]; // current partition, to be built
// we use stack arrays to have the situation saved.
int[] remainingStack = new int[n*n]; // remaining value, to be added
// int[] maxValueStack = new int[n*n]; // maximum number we can use, to prevent repeating partitions
int[] nextTryStack = new int[n*n]; // the next number we try
int[] lenStack = new int[n*n]; // length of current partition, gives us the next index in current
int head = 0; // works like a pointer, it makes stack arrays make sense.
remainingStack[0] = n;
// maxValueStack[0] = n;
nextTryStack[0] = n;
lenStack[0] = 0;
while(head >= 0){
int remaining = remainingStack[head];
// int maxValue = maxValueStack[head];
int nextTry = nextTryStack[head];
int partitionLen = lenStack[head];
if(remaining == 0){ // partition has been completed
//
int[] partition = new int[partitionLen];
System.arraycopy(current, 0, partition, 0, partitionLen);
result.add(partition);
head--;
continue;
}
if(nextTry <= 0){ // no choices left
head--;
continue;
}
int chosen = nextTry;
nextTryStack[head] = chosen - 1; // next value to be tried
current[partitionLen] = chosen; // adding selected number
// generating next number for the partition
head++;
remainingStack[head] = remaining - chosen;
// maxValueStack[head] = chosen;
nextTryStack[head] = Math.min(chosen, remaining - chosen);
lenStack[head] = partitionLen + 1;
}
int[][] output = new int[result.size()][];
for(int i = 0; i < result.size(); i++){
output[i] = result.get(i);
}
return output;
} }