常见递归问题 java

//最长公共子序列

import java.util.*;
public class Main {
public static void main(String[] args){
int ans = maxlen("abc","sdsdabc");
System.out.println(ans);
}
static int maxlen(String s1,String s2){
if(s1.length()==0||s2.length()==0) return 0;
if(s1.charAt(0)==s2.charAt(0)) return maxlen(s1.substring(1),s2.substring(1))+1;
else
return Math.max(maxlen(s1.substring(1),s2), maxlen(s1,s2.substring(1)));
}
}

//不放回取球问题
import java.util.*;
public class Main {
public static void main(String[] args){
int ans = f(2,1);
System.out.println(ans);
}
//假设有一个带颜色的球,全局会产生它的选与不选两种情况
static int f(int m,int n){
//注意顺序
if(n==0) return 1;

if(m==n)return 1;
return f(m-1,n-1)+f(m-1,n);
}
}

 

//全排列问题
import java.util.*;
public class Main {
public static void main(String[] args){
char[] s1 = "abc".toCharArray();
f(s1,0);
}
static void f(char[] s1,int k){
if(k==s1.length-1){
for(int i=0;i<s1.length;i++){
System.out.print(s1[i]+" ");

}
System.out.println();
}
for(int i=k;i<s1.length;i++){
{char temp =s1[i]; s1[i] = s1[k]; s1[k] = temp; }
f(s1,k+1);
{char temp =s1[i]; s1[i] = s1[k]; s1[k] = temp; }
}
}
}

posted on 2018-03-16 16:45  qzb!!!  阅读(325)  评论(0编辑  收藏  举报

导航