implement intPartitions method

This commit is contained in:
Ramtin Jafari
2026-06-02 15:25:04 +03:30
parent 95028697fd
commit dd399fd00a
+31 -30
View File
@@ -1,3 +1,5 @@
import java.util.ArrayList;
public class MainExercises public class MainExercises
{ {
public char[][] generateTriangle(int n) { public char[][] generateTriangle(int n) {
@@ -66,37 +68,36 @@ public class MainExercises
return result; return result;
} }
/*
integer partitioning is a combinatorics problem in discreet maths
the problem is to generate sum numbers which their summation is the input number
e.g. 1 -> all partitions of integer 3 are:
3
2, 1
1, 1, 1
e.g. 2 -> for number 4 goes as:
4
3, 1
2, 2
2, 1, 1
1, 1, 1, 1
Note: As you can see in the examples, we want to generate distinct partitions,
which means 1,2 and 2,1 are not different — they count as the same combination.
You should generate all partitions of the input number.
Hint: You can determine the size and order of the arrays by finding the pattern
of partitions and their count. Trust me, this one's fun and easy :)
If you're familiar with Lists and ArrayLists, you can also edit the method's
body to use them instead of arrays.
*/
public int[][] intPartitions(int n) { public int[][] intPartitions(int n) {
// todo ArrayList<int[]> result = new ArrayList<>();
return null; ArrayList<Integer> curPartition = new ArrayList<>();
fillPartition(n, n, curPartition, result);
return result.toArray(new int[result.size()][]);
}
private void fillPartition(int max, int remaining, ArrayList<Integer> curPartition, ArrayList<int[]> result) {
if (remaining == 0) {
int size = curPartition.size();
int[] savingArr = new int[size];
for (int i = 0; i < size; i++) {
savingArr[i] = curPartition.get(i);
}
result.add(savingArr);
return;
}
for (int i = Math.min(max, remaining); i >= 1; i--) {
curPartition.add(i);
int newRemaining = remaining - i;
fillPartition(i, newRemaining, curPartition, result);
curPartition.removeLast();
}
} }