From dd399fd00a829cd5cd095f29548aabfb2d4bca2d Mon Sep 17 00:00:00 2001 From: Ramtin Jafari Date: Tue, 2 Jun 2026 15:25:04 +0330 Subject: [PATCH] implement intPartitions method --- src/main/java/MainExercises.java | 61 ++++++++++++++++---------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 0dcbfaa..37f3b29 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,3 +1,5 @@ +import java.util.ArrayList; + public class MainExercises { public char[][] generateTriangle(int n) { @@ -66,37 +68,36 @@ public class MainExercises 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) { - // todo - return null; + ArrayList result = new ArrayList<>(); + ArrayList curPartition = new ArrayList<>(); + + fillPartition(n, n, curPartition, result); + + return result.toArray(new int[result.size()][]); + } + + private void fillPartition(int max, int remaining, ArrayList curPartition, ArrayList 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(); + } }