标签:
判断四个数是否可能通过加减乘得到二十四, 可以使用括号,思路极其像Expression Add Operators, 区别是在处理乘号的时候,一种是没有括号的,和Expression Add Operators一样,一种是带有括号的,其实就是把乘号当作加号来计算
public class Solution { public boolean solution(List<Integer> list) { return helper(list, 0); } public boolean helper(List<Integer> list, int pre) { if (list.size() == 1) { return list.get(0) == 24; } int first = list.get(0); int second = list.get(1); List<Integer> new_list = new LinkedList<Integer>(list); new_list.remove(1); new_list.remove(0); new_list.add(0, first + second); if (helper(new_list, first)) { return true; } new_list.set(0, first - second); if (helper(new_list, first)) { return true; } int tmp = (first - pre) * second + pre; new_list.set(0, tmp); if (helper(new_list, pre)) { return true; } new_list.set(0, first * second); if (helper(new_list, first)) { return true; } return false; } }
标签:
原文地址:http://www.cnblogs.com/vision-love-programming/p/5018979.html