2015年11月14日星期六

compute 24

 24点游戏。给你几个数字,判断他们做加减乘除运算是否可以得到24,顺序可以是任意的。dfs搜索搞定。。。但是这里要注意一些细节,每次计算得到新的数之后最好加入数组做下一次搜索,不然容易出错。

public class Solution {

private boolean compute(int[] nums, int target) {
boolean[] visit = new boolean[nums.length];
return helper(nums, visit, target, nums.length);
}

private boolean helper(int[] nums, boolean[] visit, int target, int c) {
if (c == 1) {
for (int i = 0; i < nums.length; i++) {
if (!visit[i]) {
return nums[i] == target;
}
}
} else {
for (int i = 0; i < nums.length; i++) {
if (visit[i])
continue;
for (int j = i + 1; j < nums.length; j++) {
if (visit[j])
continue;
int n1 = nums[i];
int n2 = nums[j];
visit[j] = true;
nums[i] = n1 + n2;
if (helper(nums, visit, target, c - 1))
return true;
nums[i] = n1 - n2;
if (helper(nums, visit, target, c - 1))
return true;
nums[i] = n2 - n1;
if (helper(nums, visit, target, c - 1))
return true;
nums[i] = n1 * n2;
if (helper(nums, visit, target, c - 1))
return true;
if (n2 != 0) {
nums[i] = n1 / n2;
if (helper(nums, visit, target, c - 1))
return true;
}
if (n1 != 0) {
nums[i] = n2 / n1;
if (helper(nums, visit, target, c - 1))
return true;
}
nums[i] = n1;
visit[j] = false;
}
}
}
return false;
}

public static void main(String args[]) {
Solution s = new Solution();
System.out.println(s.compute(new int[] { 2, 3, 2, 1 }, 24));
}

}

没有评论:

发表评论