题解 | #24点游戏算法#
24点游戏算法
http://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
import java.util.*;
public class Main {
public static boolean[]visited = new boolean[4];
public static int []nums = new int[4];
public static boolean flag = false;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
for(int i =0;i<4;i++){
nums[i]=sc.nextInt();
}
dfs(0,0);
System.out.println(flag);
}
}
public static void dfs(int start,double sum){
if(start == 4){
if(sum == 24){
flag = true;
}
}else{
start++;
for(int i =0;i<4;i++){
if(!visited[i]){
visited[i]=true;
dfs(start,sum+nums[i]);
dfs(start,sum-nums[i]);
dfs(start,sum*nums[i]);
dfs(start,sum/nums[i]);
visited[i] = false;
}
}
}
}
}
public class Main {
public static boolean[]visited = new boolean[4];
public static int []nums = new int[4];
public static boolean flag = false;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
for(int i =0;i<4;i++){
nums[i]=sc.nextInt();
}
dfs(0,0);
System.out.println(flag);
}
}
public static void dfs(int start,double sum){
if(start == 4){
if(sum == 24){
flag = true;
}
}else{
start++;
for(int i =0;i<4;i++){
if(!visited[i]){
visited[i]=true;
dfs(start,sum+nums[i]);
dfs(start,sum-nums[i]);
dfs(start,sum*nums[i]);
dfs(start,sum/nums[i]);
visited[i] = false;
}
}
}
}
}