JAVA递归经典例子

从第一天到公司就受到老大关照,把羽化从一驼大白栽培到小白一只-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基础很重要,看来的确如此。。。

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值