【发布时间】:2020-10-23 18:13:19
【问题描述】:
我有以下输入
int combinationCount = 3;
int arr[] = {1, 1, 2, 2, 3};
combinationCount 是{1,2,3},combinationCount 定义了数列的个数。例如:combinationCount = 3 表示 {1,2,3},combinationCount = 2 表示 {1,2}
数组总是排序的,我想将输出打印为如下的组合数
[1,2,3], [1,2,3], [1,2,3], [1,2,3] //I have to iterate the whole array as it is just logic for a problem
输出说明(我想打印值,而不是索引): 这只是对输出的解释,它显示了打印值的索引位置。
Index position of each value
[0, 2, 4], [0, 3, 4], [1, 2, 4], [1, 3, 4]
Example 2
int combinationCount = 2; // means combination is {1,2}
int arr[] = {1, 2, 2};
Print: [1,2], [1,2]
Example 3
int combinationCount = 3; // means combination is {1,2,3}
int arr[] = {1, 1, 3};
Print nothing
我写的程序如下:
int combinationCount = 3;
int arr[] = {1, 1, 2, 2, 3};
List<Integer> list = new ArrayList<>();
int prev = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 1) {
prev = 1;
list = new ArrayList<>();
list.add(1);
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] == prev + 1) {
prev = arr[j];
list.add(arr[j]);
} else if (arr[j] > (prev + 1)) {
break;
}
}
if (list.size() == combinationCount) {
System.out.print(list + ",");
}
} else {
break;
}
}
Output coming as
[1,2,3],[1,2,3]
不正确
我缺少循环的地方以及我们可以编写如何优化的代码?任何建议请。如有任何疑问,请告诉我。
【问题讨论】: