洛谷原题链接
思路:
相邻两个硬币之间设一个开关,每个开关只能按一次,递推的从头开始按开关。
import java.util.Scanner;
public class Main {
static char ss1[];
static char ss2[];
static boolean used[];
static int step;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String s1 = scan.next();
String s2 = scan.next();
ss1 = s1.toCharArray();
ss2 = s2.toCharArray();
used = new boolean[ss1.length];
dfs(0);
}
static void dfs(int index) {
//因为0~index-1的元素已经摆好了,所以只要看后面的元素是否也摆好了就可以结束递归了
boolean flag = true;
for(int i = index; i < ss1.length;i ++) {
if(ss1[i] != ss2[i]) {
flag = false;
break;
}
}
if(flag == true) {
System.out.print(step);
return;
}
if(ss1[index] != ss2[index]) {
used[index] = true;
if(ss1[index] == ss1[index+1]) {
ss1[index+1] = ss2[index];
}else {
ss1[index+1] = ss1[index];
}
ss1[index] = ss2[index];
step ++;
}
dfs(index+1);
}
}