JAVA递归经典例子

来源:互联网 发布:上海市市立幼儿园 知乎 编辑:程序博客网 时间:2024/04/28 02:20

从第一天到公司就受到老大关照,把羽化从一驼大白栽培到小白一只-0-,传说老大要离开公司了,有点小感伤,感谢老大在这段时间的照顾,希望老大事业增增日上,生活美满幸福~ ~

说说这次老大给我的问题,一个棋盘,一个格子放一个棋子,要求横竖不能有多个棋子,问有多少种放法?

我先以3X3和4X4的棋盘为例找规律,有兴趣的人可以自己推推看。

public class Test1{public static void main(String[] args){int a = 0;int b = 0;int c = 0;int d = 0;int x1 = 3;int x2 = 4;int k = 0;for (a = 1; a <= x1; a++){for (b = 1; b <= x1; b++){if (b == a)continue;for (c = 1; c <= x1; c++){if (c == a || c == b)continue;System.out.println("(" + 1 + "," + a + ")" + " (" + 2 + "," + b + ")" + " (" + 3+ "," + c + ")");k++;}}}System.out.println(k);System.out.println();k=0;for (a = 1; a <= x2; a++){for (b = 1; b <= x2; b++){if (b == a)continue;for (c = 1; c <= x2; c++){if (c == a || c == b)continue;for (d = 1; d <= x2; d++){if (d == a || d == b || d == c)continue;System.out.println("(" + 1 + "," + a + ")" + " (" + 2 + "," + b + ")" + " (" + 3+ "," + c + ")" + " (" + 4 + "," + d + ")");k++;}}}}System.out.println(k);}}

 

算羽化笨吧。。。虽然能正确显示着两个例子,也看出了是个排序的规律问题,但就是不知道代码如何下手,老大就提示我用递归- -,还是有点雾,所以在网上看了看递归的例子,找到了个类似的例子,改了改完成了下面的代码。

 

import java.util.ArrayList;public class Test2{private static int x = 3;private static int k = 0;private static ArrayList<Integer> sum = new ArrayList<Integer>();public static void main(String[] args){for(int i=1;i<=x;i++){sum.add(i);}permute(sum, 0, x-1);System.out.println(k);}public static void permute(ArrayList<Integer> sum, int low, int high){int i;if (low == high){String cout = "";for (i = 0; i <= high; i++)cout +="("+ (i+1) + "," +sum.get(i)+") ";System.out.println(cout);k++;}else{for (i = low; i <= high; i++){int temp =  sum.get(low);sum.set(low,sum.get(i));sum.set(i,temp);permute(sum, low + 1, high);temp = sum.get(low);sum.set(low,sum.get(i));sum.set(i,temp);}}}}

老大每次都提醒羽化JAVA基础很重要,看来的确如此。。。

若哪位有别的方式,可以给羽化发一份,大家一起提高~ ~