九數組分數(藍橋杯)

1,2,3...9 這九個數字組成一個分數,其值恰好爲1/3,如何組法?

下面的程序實現了該功能,請填寫劃線部分缺失的代碼。

public static void test(int[] x)
	{
		int a = x[0]*1000 + x[1]*100 + x[2]*10 + x[3];
		int b = x[4]*10000 + x[5]*1000 + x[6]*100 + x[7]*10 + x[8];	
		if(a*3==b) System.out.println(a + " " + b);
	}

	public static void f(int[] x, int k)
	{
		if(k>=x.length){
			test(x);
			return;
		}

		for(int i=k; i<x.length; i++){
			{int t=x[k]; x[k]=x[i]; x[i]=t;}
			f(x,k+1);
			————————  // 填空
		}
	}

	public static void main(String[] args)
	{
		int[] x = {1,2,3,4,5,6,7,8,9};	
		f(x,0);
	}

解析:這個題要求:1,2,3,4,5,6,7,8,9 這九個數字組成一個分數,說明每一個數字分別分別且只出現一次,所以說可以用全排列算法,再看看這個題,就是對全排列算法的一個應用,該題的算法模板和全排列算法差別不大,思想是一樣的,答案所在的for循環是進行數字位置調換的,調換之後每一次都要復位,所以答案應和交換時相同。

答案:{int t=x[k]; x[k]=x[i]; x[i]=t;}

代碼如下:

public class 九數組分數
{
	public static void test(int[] x)
	{
		int a = x[0]*1000 + x[1]*100 + x[2]*10 + x[3];
		int b = x[4]*10000 + x[5]*1000 + x[6]*100 + x[7]*10 + x[8];	
		if(a*3==b) System.out.println(a + " " + b);
	}

	public static void f(int[] x, int k)
	{
		if(k>=x.length){
			test(x);
			return;
		}

		for(int i=k; i<x.length; i++){
			{int t=x[k]; x[k]=x[i]; x[i]=t;}
			f(x,k+1);
			{int t=x[k]; x[k]=x[i]; x[i]=t;}  // 填空
		}
	}

	public static void main(String[] args)
	{
		int[] x = {1,2,3,4,5,6,7,8,9};	
		f(x,0);
	}
}

運行結果:

5832 17496
5823 17469

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章