If n is an even number, divide it by 2,
If n is an odd number, it is added 1 or minus 1.
Q for a given n, how can you change it to 1 with a minimal number of steps.
For example:
N= 61
n--60
N/2 30
N/2 15
n++ 16
N/2 8
N/2 4
N/2 2
N/2 1
Algorithm design: The first thought is the recursive algorithm, but think about we can dynamically plan: set A (i) for the integer I with a minimum of steps into a solution of 1, set n=i+1 then we consider a (n), if n is even, then a (n) = A (N/2) +1; If it is odd, then a (n) = Min (A ((n+1)/2+2), A ((n-1)/2 +2)). Algorithm initialization: Obviously a (1) = 0;
classTest { Public Static voidMain (string[] args) {intK = 45; int[] A =New int[k + 1]; a[1] = 1; Char[] C =New Char[k + 1]; ChangeTo1 (A, k, c); for(inti = 0; i < a.length; i++) {System.out.println (i+ "," + c[i] + "," +A[i]); } } Private Static voidChangeTo1 (int[] A,intKChar[] c) { for(inti = 2; i < a.length; i++) { if(i% 2 = = 0) {//evenA[i] = A[i/2] + 1; C[i]= ' # '; } Else { if((a[(i + 1)/2] + 2) > (a[(i-1)/2] + 2) ) {A[i]= (a[(i-1)/2] + 2); C[i]= '-'; } Else{A[i]= (a[(i + 1)/2] + 2); C[i]= ' + '; } } } } }
Q for a given n, how can you change it to 1 with a minimal number of steps