解题思路
枚举法:通过三重for循环枚举出所有可能的组合,再用条件判断语句去除有重复数字的情况。
代码如下
/*
* 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
* 思路:采用枚举法,通过三重for循环枚举出所有可能的组合,再用条件判断语句去除有重复数字的情况。
*/
public class Exercise2 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
solution(arr);
}
public static void solution(int[] arr) {
int i = 0;
int j = 0;
int k = 0;
int count = 0;
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
for (k = 0; k < arr.length; k++) {
if (i != j && j != k && i != k) {
count++;
System.out.println(100 * arr[i] + 10 * arr[j] + arr[k]);
}
}
}
}
System.out.println("可组成" + count + "个互不相同且无重复数字的三位数");
}
}
运行结果
123
124
132
134
142
143
213
214
231
234
241
243
312
314
321
324
341
342
412
413
421
423
431
432
可组成24个互不相同且无重复数字的三位数