implement intPartitions function in MainExercises
This commit is contained in:
@@ -1,3 +1,6 @@
|
|||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
public class MainExercises
|
public class MainExercises
|
||||||
{
|
{
|
||||||
|
|
||||||
@@ -44,8 +47,29 @@ public class MainExercises
|
|||||||
|
|
||||||
|
|
||||||
public int[][] intPartitions(int n) {
|
public int[][] intPartitions(int n) {
|
||||||
// todo
|
List<int[]> result = new ArrayList<>();
|
||||||
return null;
|
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][]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user