implement intPartitions function in MainExercises

This commit is contained in:
2026-04-23 01:48:40 +03:30
parent cc27506b9a
commit 594de6aeb6
+26 -2
View File
@@ -1,3 +1,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainExercises
{
@@ -44,8 +47,29 @@ public class MainExercises
public int[][] intPartitions(int n) {
// todo
return null;
List<int[]> result = new ArrayList<>();
int[] partition = new int[n];
int length = 0;
partition[length] = n;
while (true) {
result.add(Arrays.copyOf(partition, length+1));
int rem = 0;
while (length >= 0 && partition[length] == 1){
rem += partition[length];
length--;
}
if ( length < 0 ) break;
partition[length]--;
rem++;
while (rem > partition[length]) {
partition[length+1] = partition[length];
rem -= partition[length];
length++;
}
partition[length+1] = rem;
length++;
}
return result.toArray(new int[0][]);
}