1. 程式人生 > >LeetCode題679 —— 24 Game

LeetCode題679 —— 24 Game

boolean 所有 num with math pub span between aslist

You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.

Example 1:

Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24

Example 2:

Input: [1, 2, 1, 2]
Output: False

Note:

  1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
  2. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
  3. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

思路

有兩種解法,其中一種不是很理解。先來說說另一種方法,Backtracking所有可能。對於給定的四個數,首先從中選兩個數,然後對這兩個數選擇加減乘除這四種操作的一個,得出結果後從剩下的3個數中再選兩個,執行一種操作。如此這樣重復遍歷所有可能即可。

class Solution {

    boolean res = false;
    final double eps = 0.001;

    public boolean judgePoint24(int[] nums) {
        List<Double> arr = new ArrayList<>();
        
for(int n: nums) arr.add((double) n); helper(arr); return res; } private void helper(List<Double> arr){ if(res) return; if(arr.size() == 1){ if(Math.abs(arr.get(0) - 24.0) < eps) // java中double類型判斷是否相等的方法,不能直接用是否等於0判斷 res = true; return; } for (int i = 0; i < arr.size(); i++) { for (int j = 0; j < i; j++) { List<Double> next = new ArrayList<>(); Double p1 = arr.get(i), p2 = arr.get(j); next.addAll(Arrays.asList(p1+p2, p1-p2, p2-p1, p1*p2)); if(Math.abs(p2) > eps) next.add(p1/p2); if(Math.abs(p1) > eps) next.add(p2/p1); arr.remove(i); arr.remove(j); for (Double n: next){ arr.add(n); helper(arr); arr.remove(arr.size()-1); } arr.add(j, p2); arr.add(i, p1); } } } }

註意上面List集合的兩個方法:

void add(int index,
         E element)
Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
E remove(int index)
Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
Parameters:
index - the index of the element to be removed
Returns:
the element previously at the specified position

LeetCode題679 —— 24 Game