/** * 从1-5这5个数字中取出一个3位数,数字不能重复 * 三种方法1.常规方式写3个for循环 * 2.使用栈即二叉树的方式 * 3.使用list模仿二叉树 */ public class Demo { public static final Stack<String> stack = new Stack<String>(); public static final List<String> list = new ArrayList<String>(); public static final int goalDigits = 3; public static final int[] num = {0, 1, 2, 3, 4, 5}; public static int count = 0;
public static void main(String[] args) { //常规for循环(深度优先) Long startTime = System.currentTimeMillis(); calculate(num); Long endTime = System.currentTimeMillis(); System.out.println("总共" + count + "个数"); System.out.println("总耗时" + (endTime - startTime));
//栈方式(广度优先) Long startTime1 = System.currentTimeMillis(); for (int i = 1; i < num.length; i++) { numS(num[i]); } Long endTime1 = System.currentTimeMillis(); System.out.println("总共" + count + "个数"); System.out.println("总耗时" + (endTime1 - startTime1));
//list模仿Stack Long startTime2 = System.currentTimeMillis(); for (int i = 1; i < num.length; i++) { sumS(num[i]); } Long endTime2 = System.currentTimeMillis(); System.out.println("总共" + count + "个数"); System.out.println("总耗时" + (endTime2 - startTime2)); }
public static void calculate(int[] arr) { for (int i = 1; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (arr[i] != arr[j]) { for (int k = 0; k < arr.length; k++) { if (k != i && k != j) { count++; System.out.println("第" + count + "个数" + arr[i] + arr[j] + arr[k]); } } } } } }
public static void numS(int a) { stack.push(a + ""); while (!stack.isEmpty()) { String s = stack.pop(); if (isGoal(s)) { count++; System.out.println("第" + count + "个数" + s); continue; } for (int i : num) { if (!s.contains(i + "")) { stack.push(s + i); } } } }
public static void sumS(int a) { list.add(a + ""); while (list.size() > 0) { String s = list.get(list.size() - 1); list.remove(list.size() - 1); if (isGoal(s)) { count++; System.out.println("第" + count + "个数" + s); continue; } for (int j : num) { if (!s.contains(j + "")) { list.add(s + j); } } } }