Hello, I am the little gray ape, a programmer who can write bugs!
Welcome everyone to pay attention to my column " Daily Blue Bridge ". The main function of this column is to share with you the real questions of the Blue Bridge Cup provincial competitions and finals in recent years, analyze the algorithm ideas, data structures and other content that exist in it, and help you learn To more knowledge and technology!
Title: Nine Group Scores
The nine numbers 1, 2, 3...9 form a score, and its value is exactly 1/3. How to group it?
The following program implements this function, please fill in the missing code at the underline,
public class Year2015_Bt5 { public static void text(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) { text(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); } }
Note: Only write the missing code at the horizontal line, do not write any existing code or descriptive text on the title
Problem-solving ideas:
The solution to this question actually examines the idea of the full arrangement of array elements. This is also a typical algorithm case that often appears in the summary of the blue bridge cup test questions, so it is very necessary to grasp the relevant algorithms for the arrangement and combination of array elements, friends can see My article explains it in detail " [Recursion + Backtracking] Achieve the combination, arrangement and full arrangement of array elements "
Answer source code:
public class Year2015_Bt5 { public static void text(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) { text(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); } }
Sample output: