a的n次幂
package 递归算法;
public class a的n次幂 {
public static void main ( String [ ] args) {
int a = 2 ;
int n= 20 ;
int res = pow ( a, n) ;
long now = System . currentTimeMillis ( ) ;
System . out. println ( res) ;
System . out. println ( System . currentTimeMillis ( ) - now) ;
}
private static int pow ( int i, int j) {
if ( j== 0 ) return 1 ;
int res = i;
int ex = 1 ;
while ( ( ex<< 1 ) <= j) {
res*= res;
ex = ex<< 1 ;
}
return res* pow ( i, j- ex) ;
}
}
小白上楼梯
package 递归算法;
import java. util. Scanner ;
public class 小白上楼梯 {
static private int f ( int n) {
if ( n == 0 )
return 1 ;
if ( n == 1 )
return 1 ;
if ( n == 2 )
return 2 ;
return f ( n - 1 ) + f ( n - 2 ) + f ( n - 3 ) ;
}
public static void main ( String [ ] args) {
Scanner scanner = new Scanner ( System . in) ;
int n = scanner. nextInt ( ) ;
System . out. println ( f ( n) ) ;
}
}
旋转数组的最小数字
package 递归算法;
public class 旋转数组的最小数字 {
private static int min ( int [ ] arr) {
int begin = 0 ;
int end = arr. length- 1 ;
if ( arr[ begin] < arr[ end] )
return arr[ begin] ;
while ( begin+ 1 < end) {
int mid = begin + ( ( end- begin) >> 1 ) ;
if ( arr[ mid] >= arr[ begin] ) {
begin= mid;
} else {
end= mid;
}
}
return arr[ end] ;
}
public static void main ( String [ ] args) {
int [ ] arr = { 5 , 1 , 2 , 3 , 4 } ;
int res = min ( arr) ;
System . out. println ( res) ;
}
}
在有序含空字符串的数组中查找
package 递归算法;
public class 在有序含空字符串的数组中查找 {
public static void main ( String [ ] args) {
String [ ] arr = { "a" , "" , "ac" , "" , "ad" , "b" , "" , "ba" } ;
int res = indexOf ( arr, "ac" ) ;
System . out. println ( res) ;
}
private static int indexOf ( String [ ] arr, String target) {
int begin = 0 ;
int end = arr. length - 1 ;
while ( begin <= end) {
int indexMid = begin + ( begin + end) >> 1 ;
while ( arr[ indexMid] . equals ( "" ) ) {
indexMid++ ;
if ( indexMid > end) {
return - 1 ;
}
}
if ( arr[ indexMid] . compareTo ( target) > 0 ) {
end = indexMid - 1 ;
} else if ( arr[ indexMid] . compareTo ( target) < 0 ) {
begin = indexMid + 1 ;
} else {
return indexMid;
}
}
return - 1 ;
}
}
最长连续递增子序列
package 递归算法;
public class 最长连续递增子序列 {
public static void main ( String [ ] args) {
int [ ] arr = { 1 , 9 , 2 , 5 , 7 , 3 , 4 , 6 , 8 , 0 } ;
longist ( arr) ;
}
private static void longist ( int [ ] arr) {
int max_length= 0 ;
int index= 0 ;
for ( int i = 0 ; i < arr. length; i++ ) {
int length= 0 ;
for ( int j= i+ 1 ; j< arr. length; j++ ) {
if ( arr[ j] > arr[ j- 1 ] ) {
length++ ;
} else {
if ( length> max_length) {
index= i;
i+= length;
max_length= length;
}
break ;
}
}
}
for ( int i= index; i<= index+ max_length; i++ ) {
System . out. print ( arr[ i] + " " ) ;
}
}
}