题解 | #DNA序列#
24点游戏算法
http://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
不知道为什么定义要放在前面
import java.util.*;
public class Main{
static boolean[] visit = new boolean[4];
static int[] nums = new int[4];
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String ss = scan.nextLine();
String[] strs = ss.split(" ");
for(int i = 0; i<4; i++){
nums[i] = Integer.parseInt(strs[i]);
}
System.out.println(dfs(0,0));
}
}
public static boolean dfs(int k, float sum){
if(k == 4 && sum == 24){
return true;
}
for(int i = 0; i<4; i++){
if(visit[i] == false){
visit[i] = true;
if(dfs(k+1, sum+nums[i])||
dfs(k+1, sum-nums[i])||
dfs(k+1, sum*nums[i])||
dfs(k+1, sum/nums[i])){
return true;
}
visit[i] = false;
}
}
return false;
}
}