先写一下自己的思路:
写递归函数,一定要确定参数,有以下三个参数:
String str 字符串
int num 要获取的字符数
String temp 已经获取到的字符
不多说了,直接见代码:
public class Combine {
private List<String> listStr = new ArrayList<String>();
public void getMChar(String str, int num, String tmp){
if(num > 1){
for(int i=0; i < str.length() - num + 1; i++){
char c = str.charAt(i);
String nStr = str.substring(i+1);
getMChar(nStr, num - 1, tmp == null ? ""+c : tmp + c);
}
}else{
for(int i=0; i < str.length(); i++){
listStr.add(tmp + str.charAt(i));
}
}
}
public static void main(String[] args) {
Combine combine = new Combine();
String str = "abcdefghijklmnopq";
int m = 7;
long start = System.currentTimeMillis();
combine.getMChar(str, m, "");
for(int i=0; i < combine.listStr.size(); i++){
System.out.println(combine.listStr.get(i));
}
long end = System.currentTimeMillis();
System.out.println("time = "+ (end-start)+" ms");
System.out.println("result size = " + combine.listStr.size());
}
}