• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 24 Game

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:
The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
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.
You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

Backtracking: every time draw two cards, calculate the possible results, and add one result to the nextRound list.

The nextRound list will have the remaining unused cards. 

Every round the nextRound list will decrease its size by 1.

Repeat the process until nextRound list decrease to size 1.

 

 

 1 class Solution {
 2     public boolean judgePoint24(int[] nums) {
 3         List<Double> list = new ArrayList<>();
 4         for (int num : nums) {
 5             list.add((double)num);
 6         }
 7         return backtracking(list);
 8     }
 9     
10     public boolean backtracking(List<Double> list) {
11         if (list.size() == 1) {
12             if (Math.abs(list.get(0) - 24.0) < 0.001) {
13                 return true;
14             }
15             return false;
16         }
17         
18         // every time backtracking: always draw two cards
19         for (int i = 0; i < list.size(); i ++) {
20             for (int j = i + 1; j < list.size(); j ++) {
21                 
22                 // for each possible result of the two card-combination
23                 for (double c : compute(list.get(i), list.get(j))) {
24                     List<Double> nextRound = new ArrayList<>();
25                     nextRound.add(c);
26                     
27                     for (int k = 0; k < list.size(); k ++) {
28                         if (k != i && k != j) 
29                             nextRound.add(list.get(k));
30                     }
31                                     
32                     if (backtracking(nextRound)) return true;
33                 }
34             }
35         }
36         return false;
37     }
38     
39     // compute the possible result of a combination
40     public List<Double> compute(double a, double b) {
41         return Arrays.asList(a + b, a - b, b - a, a * b, a / b, b / a);
42     }
43 }

 

posted @ 2019-10-10 14:10  neverlandly  阅读(194)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3