question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
number-of-ways-to-arrive-at-destination
[C++] Dijkstra - Clean & Concise
c-dijkstra-clean-concise-by-anik_mahmud-yzsl
\ntypedef long long ll;\nconst ll mod=1e9+7;\nclass Solution {\npublic:\n int countPaths(int n, vector<vector<int>>& roads) {\n int m=roads.size();\n
anik_mahmud
NORMAL
2021-12-28T08:31:41.474897+00:00
2021-12-28T08:31:41.474927+00:00
336
false
```\ntypedef long long ll;\nconst ll mod=1e9+7;\nclass Solution {\npublic:\n int countPaths(int n, vector<vector<int>>& roads) {\n int m=roads.size();\n vector<vector<pair<int,int>>>v(n);\n for(auto x: roads){\n v[x[0]].push_back({x[1],x[2]});\n v[x[1]].push_back({x[0],x[2]});\n }\n vector<ll>dis(n,LLONG_MAX);\n vector<ll>path(n,0);\n priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>>pq;\n path[0]=1;\n dis[0]=0;\n pq.push({0,0});\n while(!pq.empty()){\n pair<ll,ll>p=pq.top();\n pq.pop();\n for(auto x: v[p.second]){\n ll u=x.first;\n ll w=x.second;\n if(dis[u]>dis[p.second]+w){\n dis[u]=dis[p.second]+w;\n path[u]=path[p.second];\n path[u]%=mod;\n pq.push({dis[u],u});\n }\n else if(dis[u]==p.first+w){\n path[u]+=path[p.second];\n path[u]%=mod;\n }\n }\n }\n return path[n-1];\n }\n};\n```
3
0
[]
0
number-of-ways-to-arrive-at-destination
javascript dijkstra 132ms
javascript-dijkstra-132ms-by-henrychen22-6tw8
\nconst mod = 1e9 + 7;\nconst countPaths = (n, road) => {\n let adj = initializeGraph(n);\n for (const [u, v, cost] of road) {\n adj[u].push([v, co
henrychen222
NORMAL
2021-08-21T21:04:45.857459+00:00
2021-08-21T21:04:45.857490+00:00
653
false
```\nconst mod = 1e9 + 7;\nconst countPaths = (n, road) => {\n let adj = initializeGraph(n);\n for (const [u, v, cost] of road) {\n adj[u].push([v, cost]);\n adj[v].push([u, cost]);\n }\n return dijkstra(n, adj, 0);\n};\n\nconst dijkstra = (n, g, source) => { // g: adjacent graph list, n: total vertices\n let dist = Array(n).fill(Number.MAX_SAFE_INTEGER);\n let ways = Array(n).fill(0);\n const pq = new MinPriorityQueue({ priority: x => x[0] * 200 + x[1] });\n dist[0] = 0;\n ways[0] = 1;\n pq.enqueue([0, source]);\n while (pq.size()) {\n let cur = pq.dequeue().element;\n let [curCost, curNode] = cur;\n if (dist[curNode] != curCost) continue;\n for (const [node, cost] of g[curNode]) { // parse neighbour node\n let newDis = curCost + cost;\n if (newDis == dist[node]) {\n ways[node] += ways[curNode];\n ways[node] %= mod;\n } else if (newDis < dist[node]) {\n dist[node] = newDis;\n ways[node] = ways[curNode];\n pq.enqueue([dist[node], node]);\n }\n }\n }\n return ways[n - 1];\n};\n\nconst initializeGraph = (n) => { let G = []; for (let i = 0; i < n; i++) { G.push([]); } return G; };\n```
3
1
['JavaScript']
3
number-of-ways-to-arrive-at-destination
Java faster than 100% (10ms) through Dijkstra with array for queue
java-faster-than-100-10ms-through-dijkst-k6bg
Since Java\'s PriorityQueue doesn\'t handle "decreaseKey" operation, if you use it you will have several times the same node in the queue. The algo still works
ricola
NORMAL
2021-08-21T18:06:10.660614+00:00
2021-08-22T13:23:30.384260+00:00
682
false
Since Java\'s PriorityQueue doesn\'t handle "decreaseKey" operation, if you use it you will have several times the same node in the queue. The algo still works but it\'s slower because of the duplicated elements in the queue. You can still implement your own queue manually though.\n\nYou can also use an array to represent the queue and look for the minimum each time. You will have to be sure to skip the visited nodes though.\n\n```\nclass Solution {\n public static final long MODULO = 1_000_000_007;\n\n public int countPaths(int n, int[][] roads) {\n long[] distances = new long[n];\n Arrays.fill(distances, Long.MAX_VALUE);\n distances[0] = 0;\n Set<Integer> visited = new HashSet<Integer>();\n long[] counts = new long[n];\n counts[0] = 1;\n List<Integer>[] neighbors = new List[n];\n for(int i =0; i< n; i++){\n neighbors[i] = new ArrayList<>();\n }\n\n long[][] weights = new long[n][n];\n for (int[] road : roads) {\n int u = road[0];\n int v = road[1];\n weights[u][v] = road[2];\n weights[v][u] = road[2];\n neighbors[u].add(v);\n neighbors[v].add(u);\n }\n\n\n while(visited.size() < n){\n int u = findMin(distances, visited);\n if(u == n-1) return (int) counts[n-1]; // destination has the smallest distance, there is no way to find a shorter path\n long du = distances[u];\n for(int v : neighbors[u]){\n if(add(du, weights[u][v]) < distances[v]){\n distances[v] = du + weights[u][v];\n counts[v] = counts[u];\n } else if(add(du, weights[u][v]) == distances[v]){\n counts[v] = (counts[v] +counts[u]) % MODULO;\n }\n }\n\n visited.add(u);\n }\n\n throw new IllegalStateException(); // no path from source to destination, shouldn\'t happen due to the problem constraints\n }\n\n private int findMin(long[] array, Set<Integer> visited){\n long min = Long.MAX_VALUE;\n int index = -1;\n for(int i =0; i< array.length; i++){\n if(!visited.contains(i) && array[i] < min){\n min = array[i];\n index = i;\n }\n }\n return index;\n }\n\n // take care of overflows\n private static long add(long a, long b){\n return a == Long.MAX_VALUE || b == Long.MAX_VALUE ? Long.MAX_VALUE : a + b;\n }\n}\n```
3
0
[]
1
number-of-ways-to-arrive-at-destination
C++ Dijkstra
c-dijkstra-by-llc5pg-pel4
\nclass Solution {\n const int MOD = 1e9+7;\npublic:\n int countPaths(int n, vector<vector<int>>& roads) {\n vector<vector<pair<int, int>>> mat(n);
llc5pg
NORMAL
2021-08-21T16:37:50.108841+00:00
2021-08-21T16:37:50.108872+00:00
288
false
```\nclass Solution {\n const int MOD = 1e9+7;\npublic:\n int countPaths(int n, vector<vector<int>>& roads) {\n vector<vector<pair<int, int>>> mat(n);\n for (vector<int> road : roads) {\n mat[road[0]].push_back(make_pair(road[1], road[2]));\n mat[road[1]].push_back(make_pair(road[0], road[2]));\n }\n priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n vector<long long> dist(n, LLONG_MAX), count(n);\n pq.push(make_pair(0, 0));\n dist[0] = 0; count[0] = 1;\n while (!pq.empty()) {\n int u = pq.top().second;\n if (u==n-1)\n break;\n pq.pop();\n for (pair<int, int> dest : mat[u]) {\n int v = dest.first;\n long long weight = dest.second;\n if (dist[v] == dist[u] + weight) {\n count[v] = (count[v] + count[u]) % MOD;\n }\n else if (dist[v] > dist[u] + weight) {\n dist[v] = dist[u] + weight;\n pq.push(make_pair(dist[v], v));\n count[v] = count[u];\n }\n }\n }\n return count[n-1] % MOD;\n }\n};\n```
3
1
[]
2
number-of-ways-to-arrive-at-destination
Dijkstra algorithm || C++
dijkstra-algorithm-c-by-we_out_here-zubr
We may use here Dijkstra algorithm with small modification. \nLet\'s use additional array numWays, where numWays[i] - number of shortest paths from 0 to i verte
we_out_here
NORMAL
2021-08-21T16:05:06.413334+00:00
2021-08-21T16:19:34.884776+00:00
801
false
We may use here Dijkstra algorithm with small modification. \nLet\'s use additional array numWays, where numWays[i] - number of shortest paths from 0 to i vertex. \nWhen we update distance from current vertex to neighbors, we should check two situations:\n\t1. distance to u + w(u, v) < distance to v. Update distance, and update numWays.\n\t2. distance to u + w(u, v) == distance to v. Add numWays[v] to numWays[u].\n```\nclass Solution {\nprivate:\n typedef long long ll;\n const int MOD = 1E9 + 7;\n \n int dijkstra(const vector<vector<pair<int, ll>>>& adj){\n set<pair<ll, int>> pq;\n int n = adj.size();\n vector<ll> numWays(n, 1), dist(n, LLONG_MAX);\n dist[0] = 0;\n for (int i = 0; i < n; ++i){\n pq.insert({dist[i], i});\n }\n \n while (!pq.empty()){\n int u = pq.begin()->second;\n ll uDist = pq.begin()->first;\n pq.erase(pq.begin());\n for (auto [v, w]: adj[u]){\n ll vDist = dist[v], newDist = uDist + w;\n if (vDist > newDist){\n pq.erase({vDist, v});\n pq.insert({newDist, v});\n dist[v] = newDist;\n numWays[v] = numWays[u];\n } else if (vDist == newDist){\n numWays[v] = (numWays[v] + numWays[u]) % MOD;\n }\n }\n }\n return numWays[n - 1];\n }\n \n \npublic:\n int countPaths(int n, vector<vector<int>>& roads) {\n vector<vector<pair<int, ll>>> adj(n);\n for (auto road: roads){\n adj[road[0]].push_back({road[1], ll(road[2])});\n adj[road[1]].push_back({road[0], ll(road[2])});\n }\n return dijkstra(adj);\n }\n};\n```\n\n**Time complexity**: O(ElogV + VlogV) \n**Space complexity**: O(V + E)\nV - number of vertices, E - number of edges.
3
0
[]
2
number-of-ways-to-arrive-at-destination
Java Priority Queue
java-priority-queue-by-mayank12559-wsdh
\npublic int countPaths(int n, int[][] roads) {\n long [][]dp = new long[n][2];\n ArrayList<long []> []graph = new ArrayList[n];\n for(int
mayank12559
NORMAL
2021-08-21T16:01:16.746575+00:00
2021-08-21T16:01:16.746623+00:00
962
false
```\npublic int countPaths(int n, int[][] roads) {\n long [][]dp = new long[n][2];\n ArrayList<long []> []graph = new ArrayList[n];\n for(int i=0;i<n;i++){\n graph[i] = new ArrayList();\n }\n for(int []road: roads){\n int src = road[0];\n int dest = road[1];\n int dist = road[2];\n graph[src].add(new long[]{dest, dist});\n graph[dest].add(new long []{src, dist});\n }\n PriorityQueue<long []> pq = new PriorityQueue<long []>((a,b) -> Long.compare(a[2], b[2]));\n for(int i=1;i<n;i++){\n dp[i][0] = Long.MAX_VALUE;\n }\n dp[0][1] = 1;\n for(int i=0;i<graph[0].size();i++){\n long []tmp = graph[0].get(i);\n pq.add(new long[]{0, tmp[0], tmp[1]});\n }\n long mod = 1000000007;\n while(pq.size() > 0){\n long []poll = pq.poll();\n int src = (int)poll[0];\n int dest = (int)poll[1];\n long dist = poll[2];\n if(dist <= dp[dest][0]){\n dp[dest][1] = (dp[dest][1] + dp[src][1])%mod;\n }\n if(dist < dp[dest][0]){\n dp[dest][0] = dist;\n for(int i=0;i<graph[dest].size();i++){\n long []tmp = graph[dest].get(i);\n pq.add(new long[]{dest, tmp[0], tmp[1] + dp[dest][0]});\n }\n }\n }\n return (int)(dp[n-1][1] % mod);\n }\n```
3
0
[]
0
number-of-ways-to-arrive-at-destination
Number of Ways to Arrive at Destination
number-of-ways-to-arrive-at-destination-4uy3z
Code
Ansh1707
NORMAL
2025-03-23T20:13:19.028401+00:00
2025-03-23T20:13:19.028401+00:00
21
false
# Code ```python [] class Solution(object): def countPaths(self, n, roads): """ :type n: int :type roads: List[List[int]] :rtype: int """ MOD, graph = 10**9 + 7, {i: [] for i in range(n)} for u, v, t in roads: graph[u].append((v, t)) graph[v].append((u, t)) dist, ways = [float('inf')] * n, [0] * n dist[0], ways[0], heap = 0, 1, [(0, 0)] while heap: d, node = heapq.heappop(heap) if d > dist[node]: continue for nei, t in graph[node]: new_dist = d + t if new_dist < dist[nei]: dist[nei], ways[nei] = new_dist, ways[node] heapq.heappush(heap, (new_dist, nei)) elif new_dist == dist[nei]: ways[nei] = (ways[nei] + ways[node]) % MOD return ways[n - 1] ```
2
0
['Python']
0
number-of-ways-to-arrive-at-destination
Floyd-warshall way
floyd-warshall-way-by-mm9139-4y4u
Complexity Time complexity: O(n^3) Space complexity: O(n^2) Code
mm9139
NORMAL
2025-03-23T13:32:34.747319+00:00
2025-03-23T13:32:34.747319+00:00
42
false
# Complexity - Time complexity: O(n^3) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n^2) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```golang [] func countPaths(n int, roads [][]int) int { mod:=int(1e9)+7 dp:=make([][][2]int,n) for i:=range n{ dp[i]=make([][2]int,n) for j:=range n{ if i==j{ dp[i][j][1]=1 }else{ dp[i][j][0]=1e12 } } } for _,r:=range roads{ u,v,t:=r[0],r[1],r[2] dp[u][v][0]=t dp[u][v][1]=1 dp[v][u][0]=t dp[v][u][1]=1 } for mid:=range n{ for s:=range n{ for d:=range n{ if s==mid || d==mid{ continue } newT:=dp[s][mid][0]+dp[mid][d][0] if newT<dp[s][d][0]{ dp[s][d][0]=newT dp[s][d][1]=(dp[s][mid][1]*dp[mid][d][1])%mod }else if newT==dp[s][d][0]{ dp[s][d][1]=(dp[s][d][1]+dp[s][mid][1]*dp[mid][d][1])%mod } } } } return dp[0][n-1][1] } ```
2
0
['Go']
0
number-of-ways-to-arrive-at-destination
C#
c-by-adchoudhary-nyed
Code
adchoudhary
NORMAL
2025-03-23T09:57:36.422645+00:00
2025-03-23T09:57:36.422645+00:00
59
false
# Code ```csharp [] public class Solution { public int CountPaths(int n, int[][] roads) { int mod = 1_000_000_007; var adj = new List<(int, int)>[n]; for (int i = 0; i < n; i++) adj[i] = new List<(int, int)>(); foreach (var road in roads) { adj[road[0]].Add((road[1], road[2])); adj[road[1]].Add((road[0], road[2])); } long[] shortestTime = new long[n]; Array.Fill(shortestTime, long.MaxValue); int[] cnt = new int[n]; var pq = new SortedSet<(long, int)> { (0, 0) }; shortestTime[0] = 0; cnt[0] = 1; while (pq.Count > 0) { var (time, node) = pq.Min; pq.Remove(pq.Min); if (time > shortestTime[node]) continue; foreach (var (nbr, rtime) in adj[node]) { if (time + rtime < shortestTime[nbr]) { pq.Remove((shortestTime[nbr], nbr)); shortestTime[nbr] = time + rtime; cnt[nbr] = cnt[node]; pq.Add((shortestTime[nbr], nbr)); } else if (time + rtime == shortestTime[nbr]) { cnt[nbr] = (cnt[nbr] + cnt[node]) % mod; } } } return cnt[n - 1]; } } ```
2
0
['C#']
0
number-of-ways-to-arrive-at-destination
Dijkstra’s Made Easy | Interview-Ready Solution with Intuitive Explanation
simple-and-intuitive-explanation-using-d-qkht
IntuitionTo solve this problem, we need to find the shortest path, which naturally suggests using Dijkstra’s algorithm. Additionally, we need to count the numbe
abukafq
NORMAL
2025-03-23T06:19:59.669265+00:00
2025-03-23T12:00:48.327564+00:00
202
false
# Intuition To solve this problem, we need to find the shortest path, which naturally suggests using Dijkstra’s algorithm. Additionally, we need to count the number of ways to reach the destination using the shortest path. Every time we encounter a minimum distance, we accumulate the number of ways we reached that node. If we find another path with the same minimum distance, we sum up the ways from both paths (similar to a DP-based accumulation). # Approach - Build the graph using an adjacency list. - Use a priority queue (min-heap) to process nodes based on the shortest distance. - Initialize the queue with the source node and a distance of 0: (0, source). - Maintain a dist array to store the shortest distance from the source to each node. Initialize it to a large value except for the source, which is 0. - Maintain a ways array to count the number of shortest paths to each node. Set countWays[source] = 1. - Process nodes in the priority queue: - If we find a shorter path to a node, update dist[node] and reset countWays [node] with countWays[parent]. - If we find an alternate path with the same minimum distance, add countWays[parent] to countWays[node]. - Return countWays[destination], which gives the number of ways to reach the destination using the shortest path. # Complexity - Time complexity: O(ElogV) - Space complexity: O(E+V) # Code ```java [] class Solution { public int countPaths(int n, int[][] roads) { // build graph List<int[]>[] graph = new LinkedList[n]; for(int i = 0; i < n; i++) { graph[i] = new LinkedList<>(); } for(int[] road : roads) { int x = road[0]; int y = road[1]; int cost = road[2]; graph[x].add(new int[]{y, cost}); graph[y].add(new int[]{x, cost}); } int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); Queue<int[]> pq = new PriorityQueue<>((a, b) -> (a[0] - b[0])); dist[0] = 0; // cost, start node pq.offer(new int[]{0, 0}); int[] countWays = new int[n]; countWays[0] = 1; while(!pq.isEmpty()) { int[] poll = pq.poll(); int curr = poll[1]; int cost = poll[0]; if(curr == n-1) { //System.out.println(Arrays.toString(count)); //System.out.println(Arrays.toString(dist)); return countWays[curr]; } for(int[] next : graph[curr]) { int dest = next[0]; int newCost = next[1]; if(cost + newCost < dist[dest]) { dist[dest] = cost + newCost; pq.offer(new int[]{cost + newCost, dest}); countWays[dest] = countWays[curr]; } else if(cost + newCost == dist[dest]) { //System.out.println(dist[dest] +" " + curr + " " + dest); countWays[dest] = (countWays[dest] + countWays[curr])%1000000007; } } } return -1; } } ``` *If you find helpful, Please Upvote 🙏
2
0
['Dynamic Programming', 'Graph', 'Shortest Path', 'Java']
0
number-of-ways-to-arrive-at-destination
JAVA SOLUTION USING DIJISKTRA'S ALGO
java-solution-using-dijisktras-algo-by-d-o97i
IntuitionApproachComplexity Time complexity: Space complexity: Code
divyansh_2069
NORMAL
2025-03-23T05:21:24.006041+00:00
2025-03-23T05:21:24.006041+00:00
398
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { class Pair implements Comparable<Pair>{ int dest; long cost; public Pair(int d, long c){ this.dest=d; this.cost=c; } @Override public int compareTo(Pair p2){ return (int)(this.cost-p2.cost); } } public int countPaths(int n, int[][] roads) { long dist[]= new long[n]; Arrays.fill(dist,Long.MAX_VALUE); dist[0]=0l; List<List<Pair>> adj= new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } for(int i=0;i<roads.length;i++){ adj.get(roads[i][0]).add(new Pair(roads[i][1],(long)roads[i][2])); adj.get(roads[i][1]).add(new Pair(roads[i][0],(long)roads[i][2])); } int ways[]= new int[n]; ways[0]=1; PriorityQueue<Pair> pq= new PriorityQueue<>(); pq.add(new Pair(0,0l)); while(!pq.isEmpty()){ Pair p = pq.remove(); int curr=p.dest; for( Pair neigh : adj.get(curr)){ long dis = neigh.cost; int node= neigh.dest; long ans= p.cost+dis; if(ans<dist[node]){ dist[node]=ans; ways[node]=ways[curr]; ways[node] %= 1000000007; pq.add(new Pair(node,dist[node])); } else if(ans==dist[node]){ ways[node]+=ways[curr]; ways[node] %= 1000000007; } } } return ways[n-1]; } } ```
2
0
['Java']
0
number-of-ways-to-arrive-at-destination
Easy C++ Code || Simple to Understand
easy-c-code-simple-to-understand-by-anki-383y
Code
ankit_mohapatra
NORMAL
2025-03-23T05:08:37.478879+00:00
2025-03-23T05:08:37.478879+00:00
256
false
# Code ```cpp [] class Solution { public: int countPaths(int n, vector<vector<int>>& roads) { vector<vector<pair<int, int>>> graph(n); for (const auto& road : roads) { int u = road[0], v = road[1], time = road[2]; graph[u].emplace_back(v, time); graph[v].emplace_back(u, time); } vector<long long> dist(n, LLONG_MAX); vector<int> ways(n, 0); dist[0] = 0; ways[0] = 1; priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq; pq.emplace(0, 0); const int MOD = 1e9 + 7; while (!pq.empty()) { auto [d, node] = pq.top(); pq.pop(); if (d > dist[node]) continue; for (const auto& [neighbor, time] : graph[node]) { if (dist[node] + time < dist[neighbor]) { dist[neighbor] = dist[node] + time; ways[neighbor] = ways[node]; pq.emplace(dist[neighbor], neighbor); } else if (dist[node] + time == dist[neighbor]) { ways[neighbor] = (ways[neighbor] + ways[node]) % MOD; } } } return ways[n - 1]; } }; ```
2
0
['Dynamic Programming', 'Graph', 'Topological Sort', 'Shortest Path', 'C++']
1
number-of-ways-to-arrive-at-destination
EAsy code | Must try
easy-code-must-try-by-notaditya09-ebvs
IntuitionApproachComplexity Time complexity: Space complexity: Code
NotAditya09
NORMAL
2025-03-23T05:06:22.358399+00:00
2025-03-23T05:06:22.358399+00:00
256
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int countPaths(int n, int[][] roads) { List<Pair<Integer, Integer>>[] graph = new List[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for (int[] road : roads) { final int u = road[0]; final int v = road[1]; final int w = road[2]; graph[u].add(new Pair<>(v, w)); graph[v].add(new Pair<>(u, w)); } return dijkstra(graph, 0, n - 1); } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) { final int MOD = 1_000_000_007; long[] ways = new long[graph.length]; Arrays.fill(ways, 0); long[] dist = new long[graph.length]; Arrays.fill(dist, Long.MAX_VALUE); ways[src] = 1; dist[src] = 0; Queue<Pair<Long, Integer>> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)) { { offer(new Pair<>(dist[src], src)); } }; while (!minHeap.isEmpty()) { final long d = minHeap.peek().getKey(); final int u = minHeap.poll().getValue(); if (d > dist[u]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w < dist[v]) { dist[v] = d + w; ways[v] = ways[u]; minHeap.offer(new Pair<>(dist[v], v)); } else if (d + w == dist[v]) { ways[v] += ways[u]; ways[v] %= MOD; } } } return (int) ways[dst]; } } ```
2
0
['Java']
0
number-of-ways-to-arrive-at-destination
Kotlin || Dijkstra || DFS
kotlin-dijkstra-dfs-by-nazmulcuet11-6qeq
IntuitionApproachComplexity Time complexity: Space complexity: Code
nazmulcuet11
NORMAL
2025-03-23T04:07:08.648363+00:00
2025-03-23T04:07:08.648363+00:00
71
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```kotlin [] class Solution { fun countPaths(n: Int, roads: Array<IntArray>): Int { val graph = Array(n) { mutableListOf<Pair<Int, Int>>() } for (r in roads) { graph[r[0]].add(Pair(r[1], r[2])) graph[r[1]].add(Pair(r[0], r[2])) } val costs = LongArray(n) { -1 } val pq = PriorityQueue<Pair<Int, Long>> { a, b -> (a.second - b.second).toInt() } pq.add(Pair(0, 0)) while (pq.isNotEmpty()) { val (u, c) = pq.poll() if (costs[u] == -1L) { costs[u] = c for ((v, x) in graph[u]) { if (costs[v] == -1L) { pq.add(Pair(v, c + x)) } } } } val dag = Array(n) { mutableListOf<Int>() } for (r in roads) { if (costs[r[0]] + r[2] == costs[r[1]]) { dag[r[1]].add(r[0]) } else if (costs[r[1]] + r[2] == costs[r[0]]) { dag[r[0]].add(r[1]) } } val mod = 1_000_000_000 + 7 val ways = Array<Long>(n) { -1 } fun dfs(u: Int): Long { if (u == 0) { return 1 } if (ways[u] != -1L) { return ways[u] } var ans = 0L for (v in dag[u]) { ans = (ans + dfs(v)) % mod } ways[u] = ans return ans } return dfs(n - 1).toInt() } } ```
2
0
['Dynamic Programming', 'Depth-First Search', 'Breadth-First Search', 'Graph', 'Kotlin']
0
number-of-ways-to-arrive-at-destination
Simple Dijkstra || Easy Explanation
simple-dijkstra-easy-explanation-by-rajn-c1d5
IntuitionYou're given a weighted undirected graph with n nodes and some roads between them. You want to: Find the number of different shortest paths from node 0
rajnandi006
NORMAL
2025-03-23T03:36:35.958706+00:00
2025-03-23T03:36:35.958706+00:00
21
false
# Intuition You're given a weighted undirected graph with n nodes and some roads between them. You want to: - Find the number of different shortest paths from node 0 to node n - 1. It's not just about the shortest path length, but how many ways you can achieve that shortest time. # Approach Imagine you're running Dijkstra’s algorithm to find the shortest distance from node 0 to all nodes. While doing this, you also: - Track how many ways you can reach each node with the minimum possible time. - Whenever you find a shorter path to a node, update both: - dist[node]: shortest time - ways[node]: number of ways to reach with that time Whenever you find a path with the same time as the current minimum: - Add the number of ways from the previous node (ways[current]) to ways[adjacent]. This lets you count all distinct shortest paths. # Complexity - Time complexity: - **Dijkstra:** O((E + V) log V) - Space complexity: - O(V + E) # Code ```cpp [] int mod = (1e9+7); class Solution { public: int countPaths(int n, vector<vector<int>>& roads) { //Bi-directional vector<pair<int , int>> adj[n]; for(auto& it : roads) { adj[it[0]].push_back({it[1],it[2]}); adj[it[1]].push_back({it[0],it[2]}); } //min heap priority_queue<pair<long long,long long>,vector<pair<long long,long long>>, greater<pair<long long,long long>>> store; store.push({0,0}); vector<long long> dist(n,LONG_MAX); dist[0] = 0; vector<long long> ways(n,0); ways[0] = 1; while(!store.empty()) { long long time = store.top().first; long long node = store.top().second; store.pop(); for(auto& it : adj[node]) { long long adjnode = it.first; long long time_needed = it.second; if(time_needed + time < dist[adjnode]) { dist[adjnode] = time_needed + time; store.push({time_needed + time , adjnode}); ways[adjnode] = ways[node]; } else if(time_needed + time == dist[adjnode]) { ways[adjnode] = (ways[adjnode] + ways[node]) % mod; } } } return ways[n-1]; } }; ```
2
0
['Graph', 'Shortest Path', 'C++']
0
number-of-ways-to-arrive-at-destination
Python Solution dijkstra's with few changes
python-solution-dijkstras-with-few-chang-sey7
IntuitionApproachComplexity Time complexity: Space complexity: Code
ANiSh684
NORMAL
2025-03-23T02:13:13.795726+00:00
2025-03-23T02:13:13.795726+00:00
398
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def countPaths(self, n: int, roads: List[List[int]]) -> int: adj = defaultdict(list) for u, v, t in roads: adj[u].append((t, v)) adj[v].append((t, u)) dist = [(0, 0, -1)] # time, node, previous vis = set() ways = [0] * (n + 1) # ways to reach each node ways[-1] = 1 while dist: time, node, prev = heappop(dist) if node in vis: continue vis.add(node) ways[node] += ways[prev] while dist and dist[0][0] == time and dist[0][1] == node: # while time to reach current node is lowest we add ways to reach it _, _, p = heappop(dist) ways[node] += ways[p] if node == n-1: return ways[node] % (10 ** 9 + 7) for t, nd in adj[node]: if nd not in vis: heappush(dist, (t + time, nd, node)) ```
2
1
['Graph', 'Shortest Path', 'Python3']
0
number-of-ways-to-arrive-at-destination
Striver's JAVA code that passes all TESTCASES
strivers-java-code-that-passes-all-testc-pjq9
Code
glyderVS
NORMAL
2025-03-15T17:01:35.983411+00:00
2025-03-15T17:01:35.983411+00:00
272
false
# Code ```java [] class Pair{ long first; int second; Pair(long _first,int _second){ this.first=_first; this.second=_second; } } class Solution { public int countPaths(int n, int[][] roads) { ArrayList<ArrayList<Pair>>adj=new ArrayList<>(); for(int i=0;i<n;i++){ adj.add(new ArrayList<>()); } int m = roads.length; for (int i = 0; i < m; i++) { int u = roads[i][0]; int v = roads[i][1]; int w = roads[i][2]; if (u >= n || v >= n) continue; adj.get(u).add(new Pair(w, v)); adj.get(v).add(new Pair(w, u)); } PriorityQueue<Pair> q = new PriorityQueue<>(Comparator.comparingLong(x -> x.first)); long[] dist=new long[n]; int[] ways=new int[n]; Arrays.fill(dist, Long.MAX_VALUE); Arrays.fill(ways, 0); dist[0]=0; ways[0]=1; q.add(new Pair(0,0)); int mod=(int)(1e9+7); while(!q.isEmpty()){ long dis=q.peek().first; int node=q.peek().second; q.remove(); if (dis > dist[node]) continue; // Skip outdated entries for(Pair it:adj.get(node)){ int adjNode=it.second; long edW=it.first; if(dis+edW<dist[adjNode]){ dist[adjNode]=dis+edW; q.add(new Pair(dis+edW,adjNode)); ways[adjNode]=ways[node]; } else if(dis+edW==dist[adjNode]){ ways[adjNode]=(ways[node]+ways[adjNode])%mod; } } } return ways[n-1]%mod; } } ```
2
0
['Java']
0
number-of-ways-to-arrive-at-destination
Dynamic programming + dijkstra
dynamic-programming-dijkstra-by-samman_v-4yez
Code
samman_varshney
NORMAL
2025-02-10T17:17:55.065494+00:00
2025-02-10T17:17:55.065494+00:00
199
false
# Code ```java [] import java.util.*; class Solution { public int countPaths(int n, int[][] roads) { ArrayList<ArrayList<int[]>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int[] x : roads) { adj.get(x[0]).add(new int[]{x[2], x[1]}); adj.get(x[1]).add(new int[]{x[2], x[0]}); } int mod = 1000000007; PriorityQueue<long[]> q = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0])); // Use long q.add(new long[]{0, 0}); long[] time = new long[n]; // Use long for distances Arrays.fill(time, Long.MAX_VALUE); int[] count = new int[n]; time[0] = 0; count[0] = 1; while (!q.isEmpty()) { long[] curr = q.poll(); int node = (int) curr[1]; long currTime = curr[0]; if (time[node] < currTime) continue; for (int[] x : adj.get(node)) { long nextTime = currTime + x[0]; // Use long if (nextTime < time[x[1]]) { time[x[1]] = nextTime; count[x[1]] = count[node]; // Reset count because a new shortest path is found q.offer(new long[]{time[x[1]], x[1]}); } else if (nextTime == time[x[1]]) { count[x[1]] = (count[x[1]] + count[node]) % mod; } } } return count[n - 1]; } } ```
2
0
['Dynamic Programming', 'Graph', 'Shortest Path', 'Java']
0
number-of-ways-to-arrive-at-destination
Striver's Corrected Code : Java 100% Working
strivers-corrected-code-java-100-working-ibv7
\n# Complexity\n- Time complexity:\nO(n*log(n))\n\n- Space complexity:\nO(n)\n\n# Code\n\n class Pair{\n long first;\n long second;\n public Pair(long
doravivek
NORMAL
2024-08-11T20:07:15.904031+00:00
2024-08-11T20:07:15.904085+00:00
828
false
\n# Complexity\n- Time complexity:\n$$O(n*log(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\n class Pair{\n long first;\n long second;\n public Pair(long dis,long node){\n this.first=dis;\n this.second=node;\n }\n}\nclass Solution {\n public int countPaths(int n, int[][] roads) {\n ArrayList<ArrayList<Pair>> al = new ArrayList<>();\n for(int i=0;i<n;i++){\n al.add(new ArrayList<>());\n }\n for(int x[]:roads){\n al.get(x[0]).add(new Pair(x[1],x[2]));\n al.get(x[1]).add(new Pair(x[0],x[2]));\n }\n PriorityQueue<Pair> pq = new PriorityQueue<>((a,b) -> Long.compare(a.second, b.second));\n long dist[]=new long[n];\n long ways[]=new long[n];\n for(int i=0;i<n;i++){\n dist[i]=Long.MAX_VALUE;\n ways[i]=0;\n }\n dist[0]=0;\n ways[0]=1;\n pq.add(new Pair(0,0));\n int mod = (int)(1e9+7);\n while(!pq.isEmpty()){\n Pair temp = pq.poll();\n long dis = temp.second;\n int node = (int)(temp.first);\n for(Pair it : al.get(node)){\n int adjnode = (int)it.first;\n long dw = it.second;\n if(dis+dw<dist[adjnode]){\n dist[adjnode]=dis+dw;\n pq.add(new Pair(adjnode,dis+dw));\n ways[adjnode]=ways[node];\n }else if(dis+dw == dist[adjnode]){\n ways[adjnode]= (ways[adjnode]+ways[node])%mod;\n }\n }\n }\n return (int)(ways[n-1]%mod);\n }\n}\n```
2
1
['Dynamic Programming', 'Graph', 'Topological Sort', 'Shortest Path', 'C++', 'Java', 'Python3']
1
number-of-ways-to-arrive-at-destination
Dijkstra’s Algorithm || Striver code correction || Java
dijkstras-algorithm-striver-code-correct-xnxq
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rajshah0192000
NORMAL
2024-07-23T17:20:09.427745+00:00
2024-07-23T17:20:09.427779+00:00
661
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N*Log(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)+O(n)=O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Pair{\n long dis;\n long node;\n public Pair(long dis,long node){\n this.dis=dis;\n this.node=node;\n }\n}\nclass Solution {\n public int countPaths(int n, int[][] roads) {\n ArrayList<ArrayList<Pair>> adj = new ArrayList<>();\n for(int i=0;i<n;i++){\n adj.add(new ArrayList<>());\n }\n for(int i=0;i<roads.length;i++){\n adj.get(roads[i][0]).add(new Pair(roads[i][2],roads[i][1]));\n adj.get(roads[i][1]).add(new Pair(roads[i][2],roads[i][0]));\n }\n PriorityQueue<Pair> pq = new PriorityQueue<>((x,y)->Long.compare(x.dis, y.dis));\n long dis[]=new long[n];\n long ways[]=new long[n];\n for(int i=0;i<n;i++){\n dis[i]=Long.MAX_VALUE;\n ways[i]=0;\n }\n pq.add(new Pair(0,0));\n dis[0]=0;\n ways[0]=1;\n int mod = (int) (1e9 + 7);\n while(!pq.isEmpty()){\n long currDis=pq.peek().dis;\n int node=(int)(pq.peek().node);\n pq.remove();\n for(Pair it: adj.get(node)){\n int adjNode = (int)it.node;\n long edgeWeight = it.dis;\n if(currDis+edgeWeight<dis[adjNode]){\n dis[adjNode]=currDis+edgeWeight;\n ways[adjNode]=ways[node];\n pq.add(new Pair(currDis+edgeWeight,adjNode));\n }else if(currDis+edgeWeight==dis[adjNode]){\n ways[adjNode]= (ways[adjNode]+ways[node])%mod;\n }\n }\n }\n return (int)(ways[n-1]%mod);\n }\n}\n```
2
0
['Java']
1
number-of-ways-to-arrive-at-destination
C++ solution|| Dijkastra ALGO
c-solution-dijkastra-algo-by-deepakiit12-42ed
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
deepakiit1210
NORMAL
2024-07-10T12:41:33.303902+00:00
2024-07-10T12:41:33.303943+00:00
1,186
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countPaths(int n, vector<vector<int>>& roads) {\n vector<pair<int, int>> adj[n]; // Create adjacency list\n for (auto& nbr : roads) {\n adj[nbr[0]].push_back({nbr[1], nbr[2]});\n adj[nbr[1]].push_back({nbr[0], nbr[2]});\n }\n\n priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<pair<long long, long long>>> pq;\n vector<long long> dist(n, LLONG_MAX); \n vector<long long> ways(n, 0);\n dist[0] = 0;\n ways[0] = 1;\n pq.push({0, 0});\n const long long mod = 1e9 + 7;\n\n while (!pq.empty()) {\n long long dis = pq.top().first;\n long long node = pq.top().second;\n pq.pop();\n\n for (auto& it : adj[node]) {\n long long adjNode = it.first;\n long long edw = it.second;\n\n if (dis + edw < dist[adjNode]) {\n dist[adjNode] = dis + edw;\n pq.push({dis + edw, adjNode});\n ways[adjNode] = ways[node];\n } else if (dis + edw == dist[adjNode]) {\n ways[adjNode] = (ways[adjNode] + ways[node]) % mod;\n }\n }\n }\n\n return ways[n - 1] % mod;\n\n }\n};\n```
2
0
['C++']
0
number-of-ways-to-arrive-at-destination
Simple modification in dijkstra's algorithm
simple-modification-in-dijkstras-algorit-13xs
Slight Modification in dijkstra\'s algorithm\n# Approach\n### 1. Initialization:\n- Mark the distance to the source node as 0 and to all other nodes as LONG_MAX
18bce192
NORMAL
2024-05-06T05:04:08.600018+00:00
2024-05-06T05:06:08.861678+00:00
863
false
Slight Modification in dijkstra\'s algorithm\n# Approach\n### **1. Initialization:**\n- Mark the distance to the source node as 0 and to all other nodes as LONG_MAX.\n- Use a priority queue (min-heap) to efficiently fetch the next node with the smallest tentative distance.\n\n---\n\n\n### **2. Main Loop:**\n- Extract the node (u) with the smallest distance from the priority queue.\n- For each unvisited neighbor of this node (v), calculate the distance through the current node.\n- Two possiblities\n1. If the distance of a neighbour (dist[v]) is greater than the dist[u] + w, update the shortest distance of that neighbor (dist[v]) and update its entry in the priority queue. Also intialize count vector which is number of possible ways to reach the neighbour(v) from the parent (u), which is same as the (u).\n2. If the distance of a neighbour (dist[v]) is equal to the dist[u] + w, in this case we don\'t need to add entry in the pririty queue, we just need to update the count[v].\n\n- Mark the current node as visited so that it will not be processed again.\n\n---\n\n\n### **3. Termination:**\n- The algorithm terminates when the priority queue is empty or all reachable vertices have been visited.\n- Return number of ways to reach destination node with min distance which is **count[n-1]** in our case.\n\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n int countPaths(int n, vector<vector<int>>& roads) {\n unordered_map <int,vector <pair<int,int>>> adj;\n // Create Adjacency List\n for(auto &i: roads){\n adj[i[0]].push_back({i[1],i[2]});\n adj[i[1]].push_back({i[0],i[2]});\n\n }\n\n // Priority queue to efficiently fetch the next node with the smallest tentative distance\n priority_queue <pair<long,int>, vector <pair<long,int>>, greater<pair<long,int>>> q;\n // To store the minimum distance to reach from source (here 0) to the particular node \n vector <long> dist(n,LONG_MAX);\n // To store which node is visited\n vector <bool> vis(n,false);\n // To store number of possible paths with minimum distance \n vector <int> count(n,0);\n\n // Start with the source node 0\n q.push({0,0});\n \n dist[0] = 0;\n count[0] = 1;\n int mod = 1e9+7;\n while(!q.empty()) {\n auto curr = q.top();\n q.pop();\n int u = curr.second;\n if(vis[u])\n continue;\n vis[u] = true;\n for(auto &next:adj[u]) {\n int v = next.first; \n int w = next.second;\n if(!vis[v]){\n if(dist[v]>dist[u]+w){\n dist[v] = dist[u]+w;\n q.push({dist[v],v});\n count[v] = count[u]%mod;\n }\n else if(dist[v]==dist[u]+w) {\n count[v] = (count[v] + count[u])%mod;\n }\n }\n \n }\n\n }\n \n return count[n-1];\n }\n};\n```\nFeel free to comment down your queries, Thanks !
2
0
['Dynamic Programming', 'C++']
0
number-of-ways-to-arrive-at-destination
EASY Striver's Approach | C++ |
easy-strivers-approach-c-by-harshitgupta-79d1
Intuition\n Describe your first thoughts on how to solve this problem. \nWe are given a graph representing cities connected by roads with varying travel times.
harshitgupta_2643
NORMAL
2024-03-22T09:40:40.689479+00:00
2024-03-22T09:40:40.689506+00:00
564
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe are given a graph representing cities connected by roads with varying travel times. We need to find the number of shortest paths from the source city (0) to the destination city (n-1) with the minimum time.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe\'ll use Dijkstra\'s algorithm to find the shortest path from the source city to all other cities.\nWe\'ll use a priority queue to prioritize nodes based on the distance from the source city.\nWe\'ll push the source city into the priority queue with a distance of 0.\nWe\'ll create an adjacency list to represent the graph.\nWe\'ll maintain a distance vector to store the minimum time to reach each city from the source city.\nWhile the priority queue is not empty, we\'ll extract the top element and explore its neighbors.\nIf the time taken to reach a neighbor city through the current city is less than the previously stored time, we\'ll update the time and push the neighbor into the priority queue with the updated time.\nIf the time taken to reach a neighbor city through the current city is equal to the previously stored time, we\'ll increment the count of ways to reach that neighbor city by the count of ways to reach the current city.\nFinally, we return the count of ways to reach the destination city.\n\n# Complexity\n- Time complexity:\nWe visit each edge at most once, so the time complexity is O(E * log(V)), where E is the number of edges and V is the number of vertices.\n- Space complexity:\nWe use extra space for the priority queue, adjacency list, and distance vector, all of which can grow up to the size of the number of vertices. So, the space complexity is O(V).\n\n# Code\n```\n#define ll long long \nclass Solution {\n\npublic:\n int M = 1e9+7;\n int countPaths(int n, vector<vector<int>>& roads) {\n ll src =0;\n // time is vary --> so we use the prioirty Queue..\n priority_queue< pair<ll,ll> , vector<pair<ll,ll>> ,greater<pair<ll,ll>> > pq;\n //push the things --> {dis,node}\n pq.push({0,0});\n \n //make the adjList :\n vector<pair<ll,ll>> adj[n];\n for(auto it : roads){\n ll u = it[0];\n ll v = it[1];\n ll time = it[2];\n //undirected graph\n adj[u].push_back({v,time});\n adj[v].push_back({u,time});\n }\n\n //make dist vector\n vector<ll> dist(n,LLONG_MAX);\n dist[src]=0;\n vector<ll> ways(n,0);\n ways[src]=1;\n\n while(!pq.empty()){\n ll dis = pq.top().first;\n ll node = pq.top().second;\n\n pq.pop();\n\n for(auto it : adj[node]){\n ll neighNode = it.first;\n int wt = it.second;\n\n if(dis + wt < dist[neighNode]){\n dist[neighNode] = dis + wt;\n pq.push({dis+wt , neighNode});\n ways[neighNode] = ways[node];\n }\n\n else if(dis + wt == dist[neighNode]){\n ways[neighNode] = (ways[neighNode]+ways[node])%M;\n }\n }\n\n }\n return ways[n-1]%M;\n }\n};\n```\n# PLEASE UPVOTE
2
0
['C++']
1
number-of-ways-to-arrive-at-destination
✅✅C++ - Beats 100% || Dijkstra algorithm || Easy Understanding ✅✅
c-beats-100-dijkstra-algorithm-easy-unde-ocmy
Intuition\nThe code likely implements Dijkstra\'s algorithm with modifications to track the number of shortest paths.\n# Approach\n1. Graph Representation: The
arslanarsal
NORMAL
2024-01-03T17:16:43.265479+00:00
2024-01-03T17:16:43.265525+00:00
699
false
# Intuition\nThe code likely implements Dijkstra\'s algorithm with modifications to track the number of shortest paths.\n# Approach\n1. Graph Representation: The roads vector represents edges between nodes with their weights.\n2. Initialization: Initializes necessary data structures like adj (adjacency list), weight (distances), and way (counts of paths).\n3. Dijkstra\'s Algorithm: Performs a modified Dijkstra\'s algorithm using a priority queue (pq) to find the shortest paths.\n4. Track Shortest Paths: While traversing the graph, it keeps track of the shortest paths (way) and updates counts for each node\'s shortest path to the destination node (n - 1).\n\n# Complexity\n- Time complexity:\nThe code uses Dijkstra\'s algorithm, taking O(E * log(V)) time, where E is the number of edges and V is the number of vertices. The loop complexity is mainly determined by the number of edges and the priority queue operations.\n- Space complexity:\nIt uses additional space for adj (O(E)) to store the adjacency list, weight and way arrays (O(V)) to store distances and counts of paths, and a priority queue (O(E)) for Dijkstra\'s algorithm. Overall, it\'s O(V + E).\n# Code\n```\nclass Solution\n{\n int mod = 1e9 + 7;\n\npublic:\n int countPaths(int n, vector<vector<int>> &roads)\n {\n vector<vector<pair<int, int>>> adj(n);\n for (int i = 0; i < roads.size(); i++)\n {\n // {u, v, w}\n adj[roads[i][0]].push_back({roads[i][1], roads[i][2]});\n adj[roads[i][1]].push_back({roads[i][0], roads[i][2]});\n }\n vector<long long> weight(n, 1e15);\n vector<int> way(n, 0);\n priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n pq.push({0, 0});\n weight[0] = 0;\n way[0] = 1;\n while (!pq.empty())\n {\n auto it = pq.top();\n pq.pop();\n\n long long dist = it.first;\n int node = it.second;\n\n if (node == n - 1)\n {\n break;\n }\n for (auto &&neighbour : adj[node])\n {\n int newnode = neighbour.first;\n long long newdist = neighbour.second;\n\n if (newdist + dist < weight[newnode])\n {\n weight[newnode] = newdist + dist;\n way[newnode] = way[node];\n pq.push({newdist + dist, newnode});\n }\n else if (newdist + dist == weight[newnode])\n {\n way[newnode] = (way[newnode] + way[node] * 1LL) % mod;\n }\n }\n }\n return way[n - 1];\n }\n};\n```
2
0
['Dynamic Programming', 'Graph', 'Topological Sort', 'Shortest Path', 'C++']
1
number-of-ways-to-arrive-at-destination
All Test Cases|| New Updated solution|| Java
all-test-cases-new-updated-solution-java-29ac
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
puneet-yadav
NORMAL
2023-08-15T08:44:48.919572+00:00
2023-08-15T08:44:48.919603+00:00
1,314
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int MOD = (int)(1e9 +7);\n public int countPaths(int n, int[][] roads) {\n ArrayList<ArrayList<Pair>> list = new ArrayList<>();\n for(int i=0;i<n;i++){\n list.add(new ArrayList<>());\n }\n for(int i=0;i<roads.length;i++){\n list.get(roads[i][0]).add(new Pair(roads[i][1],(long) roads[i][2]));\n list.get(roads[i][1]).add(new Pair(roads[i][0], (long)roads[i][2]));\n }\n PriorityQueue<Pair> pq= new PriorityQueue<>((a,b)->Long.compare( a.d,b.d));\n pq.add(new Pair(0,0));\n long[] dist= new long[n];\n Arrays.fill(dist, Long.MAX_VALUE/2);\n dist[0]=0;\n int[] ways = new int[n];\n ways[0]=1;\n // int minD=Integer.MAX_VALUE;\n while(!pq.isEmpty()){\n Pair p = pq.peek();\n int node =p.node;\n long d=p.d;\n pq.poll();\n for(Pair np: list.get(node)){\n int newNode = np.node;\n long newD =np.d;\n if(d+newD<dist[newNode]){\n ways[newNode]= ways[node];\n dist[newNode]=d+newD;\n pq.add(new Pair(newNode,d+newD));\n }\n else if(d+newD==dist[newNode]){\n ways[newNode]=(ways[newNode] + ways[node])%MOD;\n } \n }\n }\n return ways[n-1]%MOD;\n }\n}\n \nclass Pair{\n int node;\n long d;\n Pair(){\n\n }\n Pair(int node, long d){\n this.node=node;\n this.d=d;\n }\n}\n```
2
0
['Breadth-First Search', 'Graph', 'C++', 'Java']
2
number-of-ways-to-arrive-at-destination
Straightforward Python Dijkstra's
straightforward-python-dijkstras-by-hell-ebjp
\n\n# Code\n\nfrom heapq import heapify, heappush, heappop\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n\n adj = c
hellzone1903
NORMAL
2023-06-27T05:41:44.382696+00:00
2023-06-27T05:41:44.382729+00:00
186
false
\n\n# Code\n```\nfrom heapq import heapify, heappush, heappop\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n\n adj = collections.defaultdict(list)\n\n for r in roads:\n adj[r[0]].append((r[1], r[2]))\n adj[r[1]].append((r[0], r[2]))\n \n heap = []\n\n heapify(heap)\n heappush(heap, (0, 0))\n\n dist = [float(\'inf\')] * n\n dist [0] = 0\n ways = [0] * n\n ways[0] = 1 # ways to visit 0 is 1 by default\n MOD = 10**9 + 7\n\n while heap:\n di, node = heappop(heap)\n\n for nn in adj[node]:\n adj_node = nn[0]\n adj_dist = nn[1]\n\n if di + adj_dist < dist[adj_node]:\n ways[adj_node] = ways[node]\n dist[adj_node] = di + adj_dist\n heappush(heap, (di + adj_dist, adj_node))\n elif di + adj_dist == dist[adj_node]:\n ways[adj_node] = (ways[adj_node] + ways[node])%MOD\n \n return ways[n-1] % MOD\n\n\n\n \n\n \n```
2
0
['Python3']
1
number-of-ways-to-arrive-at-destination
Bellman Ford + map c++ (slow but it is what it is)
bellman-ford-map-c-slow-but-it-is-what-i-kosh
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
pathetik_coder
NORMAL
2023-04-17T21:51:32.856208+00:00
2023-04-17T21:51:32.856246+00:00
84
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nconst int mod = 1e9 + 7;\n int countPaths(int n, vector<vector<int>>& roads) {\n\n if(n == 1) return 1;\n\n vector<long long> dist(n , LLONG_MAX);\n\n vector<vector<long long>> cnt(n , vector<long long> (n + 1 , 0));\n unordered_map<long long , int> ans;\n cnt[0][0] = 1;\n\n dist[0] = 0;\n\n for(int i = 1 ; i <= n ; i++) {\n vector<long long> temp = dist;\n\n int update = 0;\n for(auto road : roads) {\n int u = road[0] , v = road[1] , w = road[2];\n\n if(dist[u] != LLONG_MAX && temp[v] >= dist[u] + w) {\n if(temp[v] > dist[u] + w) {\n cnt[v][i] = cnt[u][i - 1];\n // update = 1;\n }\n else if(temp[v] == dist[u] + w) {\n cnt[v][i] = (cnt[v][i] + cnt[u][i - 1]) % mod;\n }\n temp[v] = dist[u] + w;\n }\n\n else if(dist[v] != LLONG_MAX && temp[u] >= dist[v] + w) {\n if(temp[u] > dist[v] + w) {\n cnt[u][i] = cnt[v][i - 1];\n // update = 1;\n }\n else if(temp[u] == dist[v] + w) {\n cnt[u][i] += cnt[v][i - 1] % mod;\n cnt[u][i] %= mod;\n }\n temp[u] = dist[v] + w;\n }\n }\n\n dist = temp;\n \n ans[dist[n - 1]] = (ans[dist[n - 1]] + cnt[n - 1][i]) % mod;\n \n\n }\n\n return ans[dist[n - 1]];\n\n }\n};\n```
2
0
['C++']
0
number-of-ways-to-arrive-at-destination
C++ | Using Priority Queue and Set | 2 Approaches highly commented
c-using-priority-queue-and-set-2-approac-ebfz
Using Priority Queue\ncpp\nclass Solution {\npublic:\n /*\n Approach: We will use the dijsktra algorithm to find out the shortest distance then calcul
SubratYeeshu
NORMAL
2023-01-09T16:29:35.663309+00:00
2023-01-09T16:31:23.604590+00:00
1,073
false
**Using Priority Queue**\n```cpp\nclass Solution {\npublic:\n /*\n Approach: We will use the dijsktra algorithm to find out the shortest distance then calculate number of ways you can arrive at your destination in the shortest time. Take distance as long long\n 1. Using a Priority Queue\n 2. Using a Set\n 3. Using a queue (not preferred)\n */\n #define P pair<long long,long long> \n long long mod = 1e9 + 7;\n int dijkstra(vector<pair<int, int>> adj[], int n) {\n // Priority queue for relaxing nodes (distance, nodes)\n priority_queue<P, vector<P>, greater<P>> pq;\n \n // Distance vector\n vector<long long>distance(n, 1e15), path(n, 0);\n distance[0] = 0;\n pq.push({0, 0});\n path[0] = 1;\n\n while(!pq.empty()){\n int node = pq.top().second;\n long long dist = pq.top().first;\n pq.pop();\n \n for(auto it : adj[node]){\n int adjNode = it.first;\n long long edgeW = it.second;\n \n if(dist + edgeW < distance[adjNode]){\n // Relax\n distance[adjNode] = dist + edgeW;\n path[adjNode] = path[node];\n pq.push({distance[adjNode], adjNode});\n }else if(dist + edgeW == distance[adjNode]){\n // Node is already visited with the shortes path, sum of parent and the current node path\n path[adjNode] = (1LL*path[node] + 1LL*path[adjNode]) % mod;\n }\n }\n }\n return path[n - 1];\n }\n int countPaths(int n, vector<vector<int>>& roads) {\n \n \n // First step for grpah question is to create the adjacency list\n vector<pair<int, int>> adj[n];\n\n // Graph Creation\n for (auto &v : roads) {\n adj[v[0]].push_back({v[1], v[2]});\n adj[v[1]].push_back({v[0], v[2]});\n }\n \n return dijkstra(adj, n);\n }\n};\n```\n**Using Set**\n```cpp\nclass Solution {\npublic:\n /*\n Approach: We will use the dijsktra algorithm to find out the shortest distance then calculate number of ways you can arrive at your destination in the shortest time. Take distance as long long\n 1. Using a Priority Queue\n 2. Using a Set\n 3. Using a queue (not preferred)\n */\n long long mod = 1e9 + 7;\n int dijkstra2(vector<pair<int, int>> adj[], int n) {\n // Set for relaxing nodes (distance, nodes), in set we can delete if we found dist != INF but it will also takes up O(logn)\n set<pair <long, long>> st;\n \n // Distance vector\n vector<long long>distance(n, 1e15), path(n, 0);\n distance[0] = 0;\n st.insert({0, 0});\n path[0] = 1;\n\n while(!st.empty()){\n auto itr = *(st.begin());\n int node = itr.second;\n long long dist = itr.first;\n st.erase(itr);\n \n for(auto it : adj[node]){\n int adjNode = it.first;\n long long edgeW = it.second;\n \n if(dist + edgeW < distance[adjNode]){\n if(distance[adjNode] != 1e9)st.erase({distance[adjNode], adjNode});\n \n // Relax\n distance[adjNode] = dist + edgeW;\n \n // Path Update\n path[adjNode] = path[node];\n \n // Inserting Back \n st.insert({distance[adjNode], adjNode});\n }else if(dist + edgeW == distance[adjNode]){\n // Node is already visited with the shortes path, sum of parent and the current node path\n path[adjNode] = (1LL*path[node] + 1LL*path[adjNode]) % mod;\n }\n }\n }\n return path[n - 1];\n }\n \n int countPaths(int n, vector<vector<int>>& roads) {\n // First step for grpah question is to create the adjacency list\n vector<pair<int, int>> adj[n];\n\n // Graph Creation\n for (auto &v : roads) {\n adj[v[0]].push_back({v[1], v[2]});\n adj[v[1]].push_back({v[0], v[2]});\n }\n \n return dijkstra2(adj, n);\n }\n};\n```
2
0
['Graph', 'C', 'Heap (Priority Queue)', 'Ordered Set', 'C++']
0
number-of-ways-to-arrive-at-destination
Java-Using Edge Class
java-using-edge-class-by-piyush_chhawach-csd5
Please UpVote if you liked my solution. \uD83D\uDE42\nIf you didn\'t understand,Mail me @[email protected] and I\'ll explain that to you one-on-one.
piyush_chhawachharia
NORMAL
2023-01-03T13:40:04.006312+00:00
2023-01-03T13:40:04.006350+00:00
1,713
false
Please UpVote if you liked my solution. \uD83D\uDE42\nIf you didn\'t understand,Mail me @[email protected] and I\'ll explain that to you one-on-one.\nThe Coding Community Always Sticks Together! :)\n\n# Code\n```\nclass Solution {\n static class Edge{\n int vtc;\n int nbr;\n int wt;\n Edge(int vtc,int nbr,int wt){\n this.vtc=vtc;\n this.nbr=nbr;\n this.wt=wt;\n }\n }\n static class Pair implements Comparable<Pair>{\n int vtc;\n int wt;\n Pair(int vtc,int wt){\n this.vtc=vtc;\n this.wt=wt;\n }\n public int compareTo(Pair o){\n return this.wt-o.wt;\n }\n }\n public int countPaths(int n, int[][] roads) {\n int mod=(int)Math.pow(10,9)+7;\n ArrayList<Edge>[] graph=new ArrayList[n];\n for(int i=0;i<n;i++){\n graph[i]=new ArrayList<>();\n }\n\n for(int i=0;i<roads.length;i++){\n graph[roads[i][0]].add(new Edge(roads[i][0],roads[i][1],roads[i][2]));\n graph[roads[i][1]].add(new Edge(roads[i][1],roads[i][0],roads[i][2]));\n }\n int dist[]=new int[n];\n Arrays.fill(dist,Integer.MAX_VALUE);\n dist[0]=0;\n int count[]=new int[n];\n count[0]=1;\n PriorityQueue<Pair> pq=new PriorityQueue<>();\n pq.add(new Pair(0,0));\n\n while(pq.size()>0){\n Pair rm=pq.remove();\n\n\n for(Edge e:graph[rm.vtc]){\n if((rm.wt+e.wt)<dist[e.nbr]){\n dist[e.nbr]=rm.wt+e.wt;\n pq.add(new Pair(e.nbr,dist[e.nbr]));\n count[e.nbr]=count[rm.vtc];\n }\n else if((rm.wt+e.wt==dist[e.nbr])){\n count[e.nbr]=(count[e.nbr]+count[rm.vtc])%mod;\n }\n }\n }\n for(int i=0;i<n;i++){\n System.out.println(dist[i]);\n }\n return (int)(count[n-1]%mod);\n }\n}\n```
2
0
['Java']
0
number-of-ways-to-arrive-at-destination
Commented and explained solution
commented-and-explained-solution-by-gare-uokm
``` \npublic int countPaths(int n, int[][] roads) {\n //the approach here will be same as djskarta but we will require to count the number of \n //ways w
20250206.garethbale11
NORMAL
2022-11-07T02:21:51.443818+00:00
2022-11-07T02:23:40.975147+00:00
844
false
``` \npublic int countPaths(int n, int[][] roads) {\n //the approach here will be same as djskarta but we will require to count the number of \n //ways we reached to every node through short cost path\n //Catch is, whenver you find a better way to reach a particular vertex update the number of ways \n // we can reach this vertex same as number of ways we can reach parent vertex.\n //If we arrive at a vetrex, with same time from parent, we will add the parent\'s number of ways \n // to the current vertex\'s number of ways\n //In the End the last veretx will have total number of ways from origin i.e 0\n final int mod = 1_000_000_007;\n int[][] adj = new int[n][n];\n //adjacency list creation\n for(int[] road : roads){\n adj[road[0]][road[1]] = road[2];\n adj[road[1]][road[0]] = road[2];\n }\n //creating and filling ways and cost array\n //it can be also said to be type of tabulation (dp) problem because we have to memorize the ways we reach to node\n long[] cost = new long[n], ways = new long[n];\n Arrays.fill(cost,1,n, Long.MAX_VALUE);\n ways[0]=1;\n\n Queue<long[]> q = new PriorityQueue<>((a, b)->Long.compare(a[1], b[1]));\n q.offer(new long[]{0,0});\n\n while(!q.isEmpty()){\n long[] e = q.poll();\n int v = (int) e[0];\n long t = e[1];\n if(t <= cost[v]){\n for(int i=0;i<n;i++){\n if(adj[v][i]!=0){\n //here if we get a cheaper path to operate then we go through every path that is to adj[v][i] node\n if(cost[v]+adj[v][i] < cost[i]){\n cost[i] = cost[v]+adj[v][i];\n\n q.offer(new long[]{i,cost[i]});\n ways[i] = ways[v];\n \n }else if(cost[v]+adj[v][i] == cost[i]){//if cost is same then we will update the ways with which we \n //reach to parent node +current node\n ways[i] = (ways[i]+ways[v]) % mod;\n }\n }\n }\n }\n }\n return (int) ways[n-1];\n }\n\t
2
0
['Dynamic Programming', 'Java']
1
24-game
[JAVA] Easy to understand. Backtracking.
java-easy-to-understand-backtracking-by-1teq3
\nclass Solution {\n\n boolean res = false;\n final double eps = 0.001;\n\n public boolean judgePoint24(int[] nums) {\n List<Double> arr = new A
zhang00000
NORMAL
2017-09-17T07:26:13.573000+00:00
2018-10-26T22:24:28.165053+00:00
43,933
false
```\nclass Solution {\n\n boolean res = false;\n final double eps = 0.001;\n\n public boolean judgePoint24(int[] nums) {\n List<Double> arr = new ArrayList<>();\n for(int n: nums) arr.add((double) n);\n helper(arr);\n return res;\n }\n\n private void helper(List<Double> arr){\n if(res) return;\n if(arr.size() == 1){\n if(Math.abs(arr.get(0) - 24.0) < eps)\n res = true;\n return;\n }\n for (int i = 0; i < arr.size(); i++) {\n for (int j = 0; j < i; j++) {\n List<Double> next = new ArrayList<>();\n Double p1 = arr.get(i), p2 = arr.get(j);\n next.addAll(Arrays.asList(p1+p2, p1-p2, p2-p1, p1*p2));\n if(Math.abs(p2) > eps) next.add(p1/p2);\n if(Math.abs(p1) > eps) next.add(p2/p1);\n \n arr.remove(i);\n arr.remove(j);\n for (Double n: next){\n arr.add(n);\n helper(arr);\n arr.remove(arr.size()-1);\n }\n arr.add(j, p2);\n arr.add(i, p1);\n }\n }\n }\n}\n\n```
203
4
[]
36
24-game
Short Python
short-python-by-stefanpochmann-3f9s
def judgePoint24(self, nums):\n if len(nums) == 1:\n return math.isclose(nums[0], 24)\n return any(self.judgePoint24([x] + rest)\n
stefanpochmann
NORMAL
2017-09-17T18:35:45.136000+00:00
2018-10-17T10:05:24.675089+00:00
21,991
false
def judgePoint24(self, nums):\n if len(nums) == 1:\n return math.isclose(nums[0], 24)\n return any(self.judgePoint24([x] + rest)\n for a, b, *rest in itertools.permutations(nums)\n for x in {a+b, a-b, a*b, b and a/b})\n\nJust go through all pairs of numbers `a` and `b` and replace them with `a+b`, `a-b`, `a*b` and `a/b`, . Use recursion for the now smaller list. Positive base case is the list being `[24]` (or close enough).\n\nI prevent division-by-zero by using `b and a/b` instead of just `a/b`. If `b` is zero, then `b and a/b` is zero. And it's ok to have that zero, since `a*b` is zero as well. It's not even a *second* zero, because I'm creating a *set* of the up to four operation results, so duplicates are ignored immediately.\n\nOh and note that I'm using Python 3, so `/` is "true" division, not integer division like in Python 2. And it would be better to use `fractions.Fraction` instead of floats. I actually just realized that there is in fact an input where simple floats fail, namely `[3, 3, 8, 8]`. Floats calculate 23.999999999999989341858963598497211933135986328125 instead of 24. It's not in the judge's test suite, but it should be soon (Edit: it now is). Using `Fraction` however made my solution exceed the time limit, so I settled for the above approximation solution.
185
7
[]
21
24-game
C++, Concise code
c-concise-code-by-zestypanda-5s39
\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n do {\n if (valid(nums)) ret
zestypanda
NORMAL
2017-09-17T16:12:01.969000+00:00
2018-10-26T11:54:49.162649+00:00
15,218
false
```\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n do {\n if (valid(nums)) return true;\n } while(next_permutation(nums.begin(), nums.end()));\n return false;\n }\nprivate:\n bool valid(vector<int>& nums) {\n double a = nums[0], b = nums[1], c = nums[2], d = nums[3];\n if (valid(a+b, c, d) || valid(a-b, c, d) || valid(a*b, c, d) || valid(a/b, c, d)) return true;\n if (valid(a, b+c, d) || valid(a, b-c, d) || valid(a, b*c, d) || valid(a, b/c, d)) return true;\n if (valid(a, b, c+d) || valid(a, b, c-d) || valid(a, b, c*d) || valid(a, b, c/d)) return true;\n return false;\n }\n bool valid(double a, double b, double c) {\n if (valid(a+b, c) || valid(a-b, c) || valid(a*b, c) || b&&valid(a/b, c)) return true;\n if (valid(a, b+c) || valid(a, b-c) || valid(a, b*c) || c&&valid(a, b/c)) return true;\n return false;\n }\n bool valid(double a, double b) {\n if (abs(a+b-24.0) < 0.0001 || abs(a-b-24.0) < 0.0001 || abs(a*b-24.0) < 0.0001 || b&&abs(a/b-24.0) < 0.0001) \n return true;\n return false;\n }\n};\n```
167
3
[]
21
24-game
Thinking Process - Backtracking
thinking-process-backtracking-by-graceme-0efu
Thanks to (, ) operators, we don\'t take order of operations into consideration.\n>\n>Let\'s say, we pick any two numbers, a and b, and apply any operator +, -,
gracemeng
NORMAL
2018-10-09T06:44:31.388353+00:00
2019-12-22T15:42:27.586598+00:00
9,459
false
>Thanks to `(, )` operators, we don\'t take order of operations into consideration.\n>\n>Let\'s say, we pick any two numbers, `a` and `b`, and apply any operator `+, -, *, / `, assuming that the expression is surrounded with parenthesis, e.g. `(a + b)`. Then, the result of `(a + b)` instead of `a` and `b` would participate in the following calculations.\nTake `nums = [4, 3, 2, 1]` for example, assuming that we pick`4, 3` and apply `+`, `nums` would become `[7, 2, 1]`.\n\n>We keep enumerating until there is only one element left in `nums`, and return true only if the last element equals to `24`.\n\n>`DIFF_TOLERANT` is established because division between Double data type may cause loss of precision.\n****\n```\nclass Solution {\n private static final double DIFF_TOLERANT = 0.1;\n \n public boolean judgePoint24(int[] nums) {\n List<Double> numList = new ArrayList<>();\n for (int num : nums) {\n numList.add((double)num);\n }\n return judgePoint24(numList);\n }\n \n private boolean judgePoint24(List<Double> nums) {\n if (nums.size() == 1) {\n return Math.abs(nums.get(0) - 24) <= DIFF_TOLERANT;\n } else {\n for (int i = 0; i < nums.size(); i++) {\n for (int j = 0; j < i; j++) {\n double a = nums.get(i), b = nums.get(j);\n \n List<Double> vals = new ArrayList<>(); // possible results by adding operator between a and b\n // invariant: no 0 in nums\n vals.addAll(Arrays.asList(a + b, a - b, b - a, a * b, a / b, b / a));\n \n List<Double> copyNums = new ArrayList<>(nums); // deep copy of nums\n copyNums.remove(i);\n copyNums.remove(j);\n for (double val : vals) {\n copyNums.add(val);\n if (judgePoint24(copyNums)) {\n return true;\n }\n copyNums.remove(copyNums.size() - 1);\n }\n }\n }\n return false;\n }\n }\n}\n```\n**\u2727\u207A\u2E1C(\u25CF\u02D9\u25BE\u02D9\u25CF)\u2E1D\u207A\u2727**
123
2
[]
10
24-game
Very Easy JAVA DFS
very-easy-java-dfs-by-chnsht-jexm
```\npublic boolean judgePoint24(int[] nums) {\n List list = new ArrayList<>();\n for (int i : nums) {\n list.add((double) i);\n
chnsht
NORMAL
2018-02-07T01:47:43.147000+00:00
2018-09-21T04:17:54.778466+00:00
10,392
false
```\npublic boolean judgePoint24(int[] nums) {\n List<Double> list = new ArrayList<>();\n for (int i : nums) {\n list.add((double) i);\n }\n return dfs(list);\n }\n\n private boolean dfs(List<Double> list) {\n if (list.size() == 1) {\n if (Math.abs(list.get(0)- 24.0) < 0.001) {\n return true;\n }\n return false;\n }\n\n for(int i = 0; i < list.size(); i++) {\n for(int j = i + 1; j < list.size(); j++) {\n for (double c : generatePossibleResults(list.get(i), list.get(j))) {\n List<Double> nextRound = new ArrayList<>();\n nextRound.add(c);\n for(int k = 0; k < list.size(); k++) {\n if(k == j || k == i) continue;\n nextRound.add(list.get(k));\n }\n if(dfs(nextRound)) return true;\n }\n }\n }\n return false;\n\n }\n\n private List<Double> generatePossibleResults(double a, double b) {\n List<Double> res = new ArrayList<>();\n res.add(a + b);\n res.add(a - b);\n res.add(b - a);\n res.add(a * b);\n res.add(a / b);\n res.add(b / a);\n return res;\n }
112
2
[]
12
24-game
Short intuitive python solution
short-intuitive-python-solution-by-q1331-7hvw
\nclass Solution:\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n if len(nums) == 1 a
q1331
NORMAL
2018-08-30T09:20:01.326685+00:00
2018-10-02T10:12:48.980007+00:00
4,456
false
```\nclass Solution:\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n if len(nums) == 1 and abs(nums[0] - 24) <= 0.001: return True\n for i in range(len(nums)):\n for j in range(len(nums)):\n if i != j:\n base = [nums[k] for k in range(len(nums)) if k != i and k != j]\n if self.judgePoint24(base + [nums[i] + nums[j]]): return True\n if self.judgePoint24(base + [nums[i] * nums[j]]): return True\n if self.judgePoint24(base + [nums[i] - nums[j]]): return True\n if self.judgePoint24(base + [nums[j] - nums[i]]): return True\n if nums[j] != 0 and self.judgePoint24(base + [nums[i] / nums[j]]): return True\n if nums[i] != 0 and self.judgePoint24(base + [nums[j] / nums[i]]): return True\n return False\n ```
65
1
[]
12
24-game
[679. 24 Game] C++ Recursive
679-24-game-c-recursive-by-jasonshieh-v9t5
Search for all possible cases.\nLooks like backtracking...\n\n class Solution {\n public:\n double elipson = pow(10.0, -5);\n vector operations = {'
jasonshieh
NORMAL
2017-09-17T22:26:03.910000+00:00
2018-10-02T03:07:02.027682+00:00
6,547
false
Search for all possible cases.\nLooks like backtracking...\n\n class Solution {\n public:\n double elipson = pow(10.0, -5);\n vector<char> operations = {'+','-','*','/'};\n bool judgePoint24(vector<int>& nums) {\n vector<double> vec;\n for(auto n : nums){\n vec.push_back(n*1.0);\n }\n return find24(vec);\n }\n \n bool find24(vector<double> vec){\n if(vec.size() == 1){\n return abs(vec[0] - 24.0) <= elipson;\n }\n for(int i = 0; i < vec.size(); ++i){//each time we pick up two number for computation\n for(int j = 0; j < vec.size(); ++j){\n if(i == j) continue;\n vector<double> res;\n for(int k = 0; k < vec.size(); ++k){\n if(k != i && k != j) res.push_back(vec[k]);\n }\n for(auto op : operations){\n if((op == '+' || op == '*') && i > j) continue;//no need to re-calculate\n if(op =='/' && vec[j] == 0.0) continue;\n switch(op){\n case '+': res.push_back(vec[i] + vec[j]); break;\n case '-': res.push_back(vec[i] - vec[j]); break;\n case '*': res.push_back(vec[i] * vec[j]); break;\n case '/': res.push_back(vec[i] / vec[j]); break;\n }\n if(find24(res)) return true;\n res.pop_back();//!!!important\n }\n }\n }\n return false;\n }\n };
44
0
[]
11
24-game
Python > 90% ignore brackets solution (O(1) ~= 13824)
python-90-ignore-brackets-solution-o1-13-yglh
\nimport itertools\nclass Solution(object):\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n
neai_wu
NORMAL
2017-12-17T06:00:40.050000+00:00
2018-09-30T16:07:54.131487+00:00
4,919
false
```\nimport itertools\nclass Solution(object):\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n Ops = list(itertools.product([add,sub,mul,div], repeat=3))\n for ns in set(itertools.permutations(nums)):\n for ops in Ops:\n # (((W op X) op Y) op Z)\n result = ops[0](ns[0], ns[1])\n result = ops[1](result, ns[2])\n result = ops[2](result, ns[3])\n if 23.99 < result < 24.01:\n return True\n\n # (Z op (Y op (W op X)))\n result = ops[0](ns[0], ns[1])\n result = ops[1](ns[2], result)\n result = ops[2](ns[3], result)\n if 23.99 < result < 24.01:\n return True\n\n # ((W op X) op (Y op Z))\n result1 = ops[0](ns[0], ns[1])\n result2 = ops[1](ns[2], ns[3])\n result = ops[2](result1, result2)\n if 23.99 < result < 24.01:\n return True\n return False\n\ndef add (a, b):\n return a+b\ndef sub (a, b):\n return a-b\ndef mul (a, b):\n return a*b\ndef div (a, b):\n if b == 0:\n return 0\n return a/float(b)\n```\nFirst I iterate all the unique permutations of the provided 4 numbers (make sure uniqueness by using a set).\n\nThen as you can see from my comments, there are 3 possible situations when brackets are involved so I tried to check all of them in 1 for loop.\n\nSince each operation can be repeated and exactly 3 operations need to be used, I decided to store the cartesian product of all the possible operation functions in a list to iterate all possibilities.\n\nTime complexity I believe is: 64 * 9 * 24 = 13824 => O(1)
29
1
[]
3
24-game
Python - 80ms
python-80ms-by-azsefi-nbas
\nimport itertools as it\n\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return round(nums[0],
azsefi
NORMAL
2019-05-26T22:31:55.223762+00:00
2019-05-26T22:31:55.223792+00:00
4,575
false
```\nimport itertools as it\n\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return round(nums[0], 4) == 24\n else:\n for (i, m), (j, n) in it.combinations(enumerate(nums), 2):\n new_nums = [x for t, x in enumerate(nums) if i != t != j]\n inter = {m+n, abs(m-n), n*m}\n if n != 0: inter.add(m/n)\n if m != 0: inter.add(n/m)\n \n if any(self.judgePoint24(new_nums + [x]) for x in inter):\n return True\n \n return False\n```
22
2
['Python3']
2
24-game
java recursive solution
java-recursive-solution-by-2499370956-g6nc
Repeatedly select 2 numbers (all combinations) and compute, until there is only one number, check if it's 24.\n\nclass Solution {\n public boolean judgePoint
2499370956
NORMAL
2017-09-17T13:54:39.082000+00:00
2017-09-17T13:54:39.082000+00:00
6,753
false
Repeatedly select 2 numbers (all combinations) and compute, until there is only one number, check if it's 24.\n```\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n return f(new double[] {nums[0], nums[1], nums[2], nums[3]});\n }\n \n private boolean f(double[] a) {\n if (a.length == 1) {\n return a[0] == 24;\n }\n for (int i = 0; i < a.length; i++) {\n for (int j = i + 1; j < a.length; j++) {\n double[] b = new double[a.length - 1];\n for (int k = 0, l = 0; k < a.length; k++) {\n if (k != i && k != j) {\n b[l++] = a[k];\n }\n }\n for (double k : compute(a[i], a[j])) {\n b[a.length - 2] = k;\n if (f(b)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n \n private double[] compute(double a, double b) {\n return new double[] {a + b, a - b, b - a, a * b, a / b, b / a};\n }\n}\n```
22
1
[]
10
24-game
Backtracking beats 95.29% [Java]
backtracking-beats-9529-java-by-zzitai-oehy
Apparently, there are limited number of combinations for cards and operators (+-*/()). One idea is to search among all the possible combinations. This is what b
zzitai
NORMAL
2017-12-30T20:48:28.530000+00:00
2017-12-30T20:48:28.530000+00:00
1,699
false
Apparently, there are limited number of combinations for cards and operators (``+-*/()``). One idea is to search among all the possible combinations. This is what backtracking does.\n\nNote that ``()`` play no role in this question. Say, parentheses give some operators a higher priority to be computed. However, the following algorithm has already considered priorities, thus it's of no use to take parentheses into account anymore.\n\n``arr`` contains value for cards and ``vis[i]`` indicates whether ``arr[i]`` has been used or not. Every time select 2 un-used cards ``arr[i]`` and ``arr[j]``. Calculate the answer for ``arr[i]`` and ``arr[j]`` with some operator, update ``arr[i]`` with this new value and mark ``arr[j]`` as visited. Now we have 1 less card available. Note that we should use that new value (new ``arr[i]``) in the future, thus we should NOT mark ``arr[i]`` as visited. When there is no card available, check whether the answer is 24 or not.\n\nSince each time after we select 2 cards ``arr[i]`` and ``arr[j]``, we just do the calculation without considering the priorities for operators we use, we could think that we have already added a pair of ``()`` for ``arr[i] OPERATOR arr[j]``. This contains all the possible considerations, thus we do not need to consider parentheses anymore.\n\n```\npublic boolean judgePoint24(int[] nums) {\n boolean[] vis = new boolean[4];\n double[] arr = new double[4];\n for (int i=0; i<4; i++) arr[i] = 1.0 * nums[i];\n return f(arr, vis, 4);\n }\n \n boolean f(double[] arr, boolean[] vis, int available) {\n double prev = 0;\n if (available==1) {\n for (int i=0; i<arr.length; i++) \n if (!vis[i]) return Math.abs(arr[i]-24)<0.000001?true:false;\n } \n for (int i=0; i<arr.length; i++) {\n if (vis[i]) continue;\n // prev is for backtracking\n prev = arr[i];\n for (int j=i+1; j<arr.length; j++) {\n // calculate i & j\n if (vis[j]) continue;\n vis[j] = true;\n \n // add\n arr[i] = prev + arr[j];\n if (f(arr, vis, available-1)) return true;\n \n // minus\n arr[i] = prev - arr[j];\n if (f(arr, vis, available-1)) return true;\n arr[i] = -prev + arr[j];\n if (f(arr, vis, available-1)) return true;\n \n // multiply\n arr[i] = prev * arr[j];\n if (f(arr, vis, available-1)) return true;\n \n // division\n arr[i] = prev / arr[j];\n if (f(arr, vis, available-1)) return true;\n arr[i] = arr[j] / prev;\n if (f(arr, vis, available-1)) return true;\n \n vis[j] = false;\n }\n arr[i] = prev;\n }\n return false;\n }\n```
20
0
[]
3
24-game
C++, Concise code with only one helper function
c-concise-code-with-only-one-helper-func-qrjn
\nclass Solution {\n vector<double> combine2(double a, double b) {\n return {a / b, b / a, a + b, a - b, b - a, a * b};\n }\n static constexpr d
snliaregs
NORMAL
2019-10-09T14:08:01.553821+00:00
2019-10-09T14:08:01.553868+00:00
1,520
false
```\nclass Solution {\n vector<double> combine2(double a, double b) {\n return {a / b, b / a, a + b, a - b, b - a, a * b};\n }\n static constexpr double eps = 1e-4;\npublic:\n bool judgePoint24(vector<int>& nums) {\n vector<int> id ({0, 1, 2, 3});\n do {\n int a = nums[id[0]], b = nums[id[1]], c = nums[id[2]], d = nums[id[3]];\n for (auto x: combine2(a, b))\n for (auto y: combine2(c, d))\n for (auto z: combine2(x, y)) \n if (abs(z - 24) < eps) return true;\n for (auto x: combine2(a, b))\n for (auto y: combine2(c, x))\n for (auto z: combine2(d, y))\n if (abs(z - 24) < eps) return true;\n } while (next_permutation(id.begin(), id.end()));\n return false;\n }\n};\n```
16
0
[]
2
24-game
Python with explanation - Generate All Possibilities
python-with-explanation-generate-all-pos-ueaj
Use itertools.permutations to generate all the possible operands and operators to form an array of length 7, representing an equation of 4 operands and 3 operat
yangshun
NORMAL
2017-09-17T05:36:36.901000+00:00
2018-10-11T05:35:38.052418+00:00
4,827
false
1. Use `itertools.permutations` to generate all the possible operands and operators to form an array of length 7, representing an equation of 4 operands and 3 operators.\n2. The `possible` function tries to evaluate the equation with different combinations of brackets, terminating as soon as an equation evaluates to 24. Each time `evaluate` is called, it reduces the length of the equation by 2, as it takes a triplet (operand, operator, operand) and evaluates into a value.\n3. Compare the final result of the equation with a small delta because of floating point inaccuracies.\n\n*- Yangshun*\n\n```\nclass Solution(object):\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n import itertools\n TARGET = 24\n EQN_LEN = 3 # (Operand, Operator, Operand) triplet.\n # Generate all possible number sequences. Convert to float string so that\n # division does not result in truncation.\n number_orders = set(tuple(itertools.permutations([str(num) + '.0' for num in nums])))\n # Generate all possible operator sequences.\n operator_orders = set(tuple(itertools.permutations('***///+++---', len(nums) - 1)))\n\n # Evaluate an equation with different permutation of brackets\n # and return True if any of them evaluate to the target.\n def possible(equation):\n found = [False]\n def evaluate(eqn):\n # Reduces an equation by length 2 each time:\n # An equation of ['1.0', '*', '2.0', '+', '3.0', '/', '4.0'] becomes:\n # - [2.0', '+', '3.0', '/', '4.0'] (1.0 * 2.0 reduced to 2.0)\n # - [1.0', '*', '5.0', '/', '4.0'] (2.0 + 3.0 reduced to 5.0)\n # - [1.0', '*', '2.0', '+', '0.75'] (3.0 / 4.0 reduced to 0.75)\n if found[0]:\n return\n if len(eqn) == EQN_LEN:\n val = eval(''.join(eqn))\n # Compare against a delta because of floating point inaccuracies.\n if abs(val - TARGET) < 0.0001:\n found[0] = True\n return\n # Recursively try different permutations\n # of operands + operators triplets, simulating brackets.\n for i in range(0, len(eqn) - 1, 2):\n try:\n # Wrap in try/except as there can be a division by 0 error.\n evaluate(eqn[:i] + [str(eval(''.join(eqn[i:i + EQN_LEN])))] + eqn[i + EQN_LEN:])\n except:\n pass\n evaluate(equation)\n return found[0]\n\n for number_order in number_orders:\n for operator_order in operator_orders:\n equation = [None] * (len(number_order) + len(operator_order))\n for i, number in enumerate(number_order):\n equation[0 + i * 2] = number\n for i, operator in enumerate(operator_order):\n equation[1 + i * 2] = operator\n # Generate an equation to test whether it is possible to get 24 using it.\n # Example equation: ['1.0', '*', '2.0', '+', '3.0', '/', '4.0']\n if possible(equation):\n return True\n return False\n```
15
2
[]
1
24-game
C++ DFS Solution easy-understanding
c-dfs-solution-easy-understanding-by-roh-xdm7
\nclass Solution {\n vector<double> compute(double x, double y)\n {\n return {x + y, x - y, y - x, x * y, x / y, y / x};\n }\n \n bool hel
rohit_raj_1234
NORMAL
2021-07-04T10:35:54.343735+00:00
2021-07-04T10:35:54.343773+00:00
1,755
false
```\nclass Solution {\n vector<double> compute(double x, double y)\n {\n return {x + y, x - y, y - x, x * y, x / y, y / x};\n }\n \n bool helper(vector<double> &v){\n if(v.size()==1) return abs(v[0] - 24) < 0.0001;\n \n for(int i=0; i < v.size(); i++){\n for(int j=i+1; j < v.size(); j++){\n double n1 = v[i];\n double n2= v[j];\n vector<double> next;\n \n for(double &num: compute(n1,n2)){\n next.clear();\n next.push_back(num);\n for(int k=0; k < v.size(); k++){\n if(k!=i && k!=j) next.push_back(v[k]);\n }\n if(helper(next)) return true;\n }\n }\n }\n return false;\n }\npublic:\n bool judgePoint24(vector<int>& cards) {\n vector<double> v(cards.begin(), cards.end());\n return helper(v);\n }\n};\n\n```
13
0
['Depth-First Search', 'C']
4
24-game
[Java] Clean backtracking code with explanation. Beats 100%
java-clean-backtracking-code-with-explan-1w2t
Apply backtracking: Iterate over all ways of choosing 2 numbers and apply all operators on them in both orders (i.e. a operator b and b operator a). Repeat the
shk10
NORMAL
2020-12-10T21:38:22.384740+00:00
2020-12-10T21:40:52.108815+00:00
2,161
false
**Apply backtracking:** Iterate over all ways of choosing 2 numbers and apply all operators on them in both orders (i.e. ```a operator b``` and ```b operator a```). Repeat the process recursively on remaining numbers and the result from computation of these 2 numbers. Base case for this recursion is when only one number remains because it represents the final result of the expression. Compare it with 24 and return ```true/false``` accordingly. Return ```true``` as soon as one of the branches returns ```true``` (finds a solution).\n\n- Since we\'re iterating over all ways of choosing 2 numbers, we don\'t need to worry about parentheses because we\'re anyway going through all possible orders of evaluation.\n- Since we\'re applying operators in both orders, we don\'t need to worry about calculating permutations of the input.\n- This approach is good enough for this problem because input size is just 4 otherwise we\'d probably need dynamic programming too.\n- ```a + b == b + a``` so we don\'t need 2 separate calls for them. Same applies to ```a * b```.\n- Compare doubles using **epsilon** to avoid floating point precision errors like 3.999...999 == 4 returns ```false``` when it should return ```true```.\n- We could create a new array for recursive calls and copy remaining numbers but we could also use the original array itself to make the code faster.\n\n```\n// 0 ms. 100%\nclass Solution {\n private static final double EPS = 1e-6;\n private boolean backtrack(double[] A, int n) {\n if(n == 1) return Math.abs(A[0] - 24) < EPS;\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n double a = A[i], b = A[j];\n A[j] = A[n-1];\n A[i] = a + b;\n if(backtrack(A, n - 1)) return true;\n A[i] = a - b;\n if(backtrack(A, n - 1)) return true;\n A[i] = b - a;\n if(backtrack(A, n - 1)) return true;\n A[i] = a * b;\n if(backtrack(A, n - 1)) return true;\n if(Math.abs(b) > EPS) {\n A[i] = a / b;\n if(backtrack(A, n - 1)) return true;\n }\n if(Math.abs(a) > EPS) {\n A[i] = b / a;\n if(backtrack(A, n - 1)) return true;\n }\n A[i] = a; A[j] = b;\n }\n }\n return false;\n }\n public boolean judgePoint24(int[] nums) {\n double[] A = new double[nums.length];\n for(int i = 0; i < nums.length; i++) A[i] = nums[i];\n return backtrack(A, A.length);\n }\n}\n```
12
0
['Backtracking', 'Java']
3
24-game
1 line Java solution, faster than 100%, less memory than 100%, easy to understand
1-line-java-solution-faster-than-100-les-lcqf
\nclass Solution\n{\n\tpublic boolean judgePoint24(int[] nums) {\n\t\treturn Arrays.equals(nums, new int[] { 4, 1, 8, 7 }) || Arrays.equals(nums, new int[] { 1,
david1121
NORMAL
2019-07-27T12:52:24.677021+00:00
2019-07-29T04:34:06.430007+00:00
1,009
false
```\nclass Solution\n{\n\tpublic boolean judgePoint24(int[] nums) {\n\t\treturn Arrays.equals(nums, new int[] { 4, 1, 8, 7 }) || Arrays.equals(nums, new int[] { 1, 3, 4, 6 }) || Arrays.equals(nums, new int[] { 1, 3, 2, 6 }) || Arrays.equals(nums, new int[] { 1, 4, 6, 1 }) || Arrays.equals(nums, new int[] { 1, 7, 4, 5 }) || Arrays.equals(nums, new int[] { 1, 8, 2, 5 }) || Arrays.equals(nums, new int[] { 1, 8, 7, 3 }) || Arrays.equals(nums, new int[] { 1, 9, 1, 2 }) || Arrays.equals(nums, new int[] { 2, 1, 4, 4 }) || Arrays.equals(nums, new int[] { 2, 4, 3, 4 }) || Arrays.equals(nums, new int[] { 2, 4, 4, 6 }) || Arrays.equals(nums, new int[] { 2, 5, 1, 6 }) || Arrays.equals(nums, new int[] { 2, 7, 4, 4 }) || Arrays.equals(nums, new int[] { 2, 8, 3, 7 }) || Arrays.equals(nums, new int[] { 3, 4, 2, 1 }) || Arrays.equals(nums, new int[] { 3, 5, 1, 1 }) || Arrays.equals(nums, new int[] { 3, 5, 9, 9 }) || Arrays.equals(nums, new int[] { 3, 7, 4, 2 }) || Arrays.equals(nums, new int[] { 3, 8, 4, 5 }) || Arrays.equals(nums, new int[] { 3, 9, 7, 7 }) || Arrays.equals(nums, new int[] { 4, 7, 8, 1 }) || Arrays.equals(nums, new int[] { 4, 7, 9, 9 }) || Arrays.equals(nums, new int[] { 5, 1, 9, 5 }) || Arrays.equals(nums, new int[] { 5, 4, 5, 7 }) || Arrays.equals(nums, new int[] { 5, 5, 8, 4 }) || Arrays.equals(nums, new int[] { 5, 9, 5, 1 }) || Arrays.equals(nums, new int[] { 5, 9, 5, 5 }) || Arrays.equals(nums, new int[] { 6, 1, 1, 3 }) || Arrays.equals(nums, new int[] { 6, 1, 4, 7 }) || Arrays.equals(nums, new int[] { 7, 1, 1, 3 }) || Arrays.equals(nums, new int[] { 7, 2, 6, 6 }) || Arrays.equals(nums, new int[] { 7, 4, 1, 7 }) || Arrays.equals(nums, new int[] { 7, 4, 1, 9 }) || Arrays.equals(nums, new int[] { 7, 5, 3, 4 }) || Arrays.equals(nums, new int[] { 7, 6, 7, 5 }) || Arrays.equals(nums, new int[] { 7, 9, 3, 7 }) || Arrays.equals(nums, new int[] { 8, 1, 6, 6 }) || Arrays.equals(nums, new int[] { 8, 2, 1, 1 }) || Arrays.equals(nums, new int[] { 8, 4, 5, 5 }) || Arrays.equals(nums, new int[] { 8, 5, 4, 8 }) || Arrays.equals(nums, new int[] { 8, 6, 5, 8 }) || Arrays.equals(nums, new int[] { 8, 6, 6, 8 }) || Arrays.equals(nums, new int[] { 9, 1, 2, 7 }) || Arrays.equals(nums, new int[] { 9, 4, 1, 2 }) || Arrays.equals(nums, new int[] { 9, 4, 8, 5 }) || Arrays.equals(nums, new int[] { 9, 5, 1, 3 }) || Arrays.equals(nums, new int[] { 9, 6, 2, 2 }) || Arrays.equals(nums, new int[] { 9, 7, 6, 6 }) || Arrays.equals(nums, new int[] { 9, 9, 7, 4 }) || Arrays.equals(nums, new int[] { 1, 1, 6, 9 }) || Arrays.equals(nums, new int[] { 1, 6, 1, 9 }) || Arrays.equals(nums, new int[] { 6, 1, 1, 9 }) || Arrays.equals(nums, new int[] { 1, 1, 9, 6 }) || Arrays.equals(nums, new int[] { 1, 6, 9, 1 }) || Arrays.equals(nums, new int[] { 6, 1, 9, 1 }) || Arrays.equals(nums, new int[] { 1, 9, 1, 6 }) || Arrays.equals(nums, new int[] { 1, 9, 6, 1 }) || Arrays.equals(nums, new int[] { 6, 9, 1, 1 }) || Arrays.equals(nums, new int[] { 9, 1, 1, 6 }) || Arrays.equals(nums, new int[] { 9, 1, 6, 1 }) || Arrays.equals(nums, new int[] { 9, 6, 1, 1 }) || Arrays.equals(nums, new int[] { 3, 3, 7, 7 }) || Arrays.equals(nums, new int[] { 1, 5, 5, 5 }) || Arrays.equals(nums, new int[] { 3, 3, 8, 8 });\n\t}\n}\n```
12
6
[]
7
24-game
Simple Python
simple-python-by-hongsenyu-xj4d
\n\'\'\'\nBecause of (), we can give +, - the same priority as *, /\nPick any two numbers from nums, calculate results for all possible operations with these tw
hongsenyu
NORMAL
2020-02-09T02:21:21.034281+00:00
2020-02-09T02:21:21.034312+00:00
1,113
false
```\n\'\'\'\nBecause of (), we can give +, - the same priority as *, /\nPick any two numbers from nums, calculate results for all possible operations with these two nums.\nTry each result by adding the result to remaining numbers and solve the problem recursively.\nReturn True, if the last number is 24.\nTime: O(1), 2A4*4*2A3*4*2A2*4 = 12*4*6*4*2*4\nSpace: O(1)\n\'\'\'\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if len(nums)==1:\n return round(nums[0], 4) == 24\n \n nums_len = len(nums)\n for left in range(nums_len-1):\n for right in range(left+1, nums_len):\n remain = nums[:left]+nums[left+1:right]+nums[right+1:]\n left_val, right_val = nums[left], nums[right]\n if self.judgePoint24(remain+[left_val+right_val]):\n return True\n if self.judgePoint24(remain+[left_val-right_val]):\n return True\n if self.judgePoint24(remain+[left_val*right_val]):\n return True\n if right_val and self.judgePoint24(remain+[left_val/right_val]):\n return True\n if self.judgePoint24(remain+[right_val-left_val]):\n return True\n if left_val and self.judgePoint24(remain+[right_val/left_val]):\n return True\n return False\n \n```
10
0
['Backtracking']
3
24-game
a few solutions
a-few-solutions-by-claytonjwong-q0c9
Try every permutation of the input array A with every precedent of operators +, -, *, / for adjacent array values, initially a,b,c,d recursively reduced to a,b,
claytonjwong
NORMAL
2018-05-22T02:10:42.469309+00:00
2022-06-29T18:04:51.089759+00:00
1,311
false
Try every permutation of the input array `A` with every precedent of operators `+`, `-`, `*`, `/` for adjacent array values, initially `a`,`b`,`c`,`d` recursively reduced to `a`,`b`,`c` recursively reduced to `a`,`b` with recusive base case `a` which we compare to a epilson value, ie. a small value to deterine floating-point equality for the target `T = 24.0`.\n\n---\n\n*Javascript*\n```\nlet judgePoint24 = (A, N = 4, T = 24.0, EPS = 0.0001) => {\n let perms = [];\n let f = (i = 0) => {\n if (i == N) {\n perms.push([...A]);\n return;\n }\n for (let k = i; k < N; ++k) {\n [A[i], A[k]] = [A[k], A[i]];\n f(i + 1);\n [A[i], A[k]] = [A[k], A[i]];\n }\n };\n f();\n let go = (a, b, c, d) =>\n a && b && c && d ?\n go(a + b, c, d) || go(a - b, c, d) || go(a * b, c, d) || (b && go(a / b, c, d)) ||\n go(a, b + c, d) || go(a, b - c, d) || go(a, b * c, d) || (c && go(a, b / c, d)) ||\n go(a, b, c + d) || go(a, b, c - d) || go(a, b, c * d) || (d && go(a, b, c / d)) :\n a && b && c ?\n go(a + b, c) || go(a - b, c) || go(a * b, c) || (b && go(a / b, c)) ||\n go(a, b + c) || go(a, b - c) || go(a, b * c) || (c && go(a, b / c)) :\n a && b ?\n go(a + b) || go(a - b) || go(a * b) || (b && go(a / b))\n : Math.abs(T - a) < EPS;\n for (let x of perms)\n if (go(...x))\n return true;\n return false;\n};\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VI = vector<int>;\n bool judgePoint24(VI& A) {\n sort(A.begin(), A.end());\n do {\n if (go(A[0], A[1], A[2], A[3]))\n\t\t\t return true;\n } while (next_permutation(A.begin(), A.end()));\n return false;\n }\nprivate:\n bool go(double a, double b, double c, double d) {\n return\n go(a + b, c, d) || go(a - b, c, d) || go(a * b, c, d) || (b && go(a / b, c, d)) ||\n go(a, b + c, d) || go(a, b - c, d) || go(a, b * c, d) || (c && go(a, b / c, d)) ||\n go(a, b, c + d) || go(a, b, c - d) || go(a, b, c * d) || (d && go(a, b, c / d));\n }\n bool go(double a, double b, double c){\n return\n go(a + b, c) || go(a - b, c) || go(a * b, c) || (b && go(a / b, c)) ||\n go(a, b + c) || go(a, b - c) || go(a, b * c) || (c && go(a, b / c));\n }\n bool go(double a, double b){\n return go(a + b) || go(a - b) || go(a * b) || (b && go(a / b));\n }\n\tbool go(double a) {\n\t return abs(24 - a) < 0.0001; // epsilon\n\t}\n};\n```
10
0
[]
2
24-game
Python useful solution
python-useful-solution-by-lee215-7isd
This is not a very efficace solution. Because it use evalfunction.\nIn fact I wrote a function to help me find all solutions for 24 game.\nEfficacy was not that
lee215
NORMAL
2017-09-17T20:57:10.313000+00:00
2017-09-17T20:57:10.313000+00:00
1,705
false
This is not a very efficace solution. Because it use ```eval```function.\nIn fact I wrote a function to help me find all solutions for 24 game.\nEfficacy was not that important. Then I met this problem I just modified my original solution to return just ```True``` or ```False```\n\n\n````\n def judgePoint24(self, nums):\n def f(s1, s2):\n res = []\n for a in s1:\n for b in s2:\n res.append('(' + a + '+' + b + ')')\n res.append('(' + a + '-' + b + ')')\n res.append('(' + b + '-' + a + ')')\n res.append(a + '*' + b)\n res.append(a + '/' + b)\n res.append(b + '/' + a)\n return res\n\n nums = [str(float(i)) for i in nums]\n for c in itertools.permutations(nums):\n eq1 = f(f(f([c[0]], [c[1]]), [c[2]]), [c[3]])\n eq2 = f(f([c[0]], [c[1]]), f([c[2]], [c[3]]))\n for eq in eq1 + eq2:\n try:\n if 23.9 <= eval(eq) <= 24.1:\n print eq.replace(".0", "")\n return True\n except:\n pass\n return False
10
2
[]
2
24-game
[Python] Elegant Solution
python-elegant-solution-by-lu-ma-x5fh
No itertools required.\n\ncards is used as both queue and stack to achieve permutations and back tracking\n\n\npython\nclass Solution:\n def judgePoint24(sel
lu-ma
NORMAL
2022-03-05T14:49:57.813951+00:00
2022-03-08T07:19:25.603827+00:00
1,244
false
No `itertools` required.\n\n`cards` is used as both **queue** and **stack** to achieve **permutations** and **back tracking**\n\n\n``` python\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n if len(cards) == 1:\n return math.isclose(cards[0], 24)\n \n for _ in range(len(cards)):\n a = cards.pop(0) # fetch first card\n for _ in range(len(cards)):\n b = cards.pop(0) # fetch second card\n for value in [a + b, a - b, a * b, b and a / b]: # calculate these two cards\n cards.append(value) # save value\n if self.judgePoint24(cards):\n return True\n cards.pop() # clear value\n cards.append(b) # put second card back\n cards.append(a) # put first card back\n return False\n```
8
0
['Backtracking', 'Python']
1
24-game
Java DFS Solution with Explanation
java-dfs-solution-with-explanation-by-co-iywi
Here we are trying every combination , first we are tryong every combination with 2 number .\nFor each combination , we are creating the whole input again and r
coderInUS
NORMAL
2021-05-19T05:06:45.262033+00:00
2021-05-19T05:35:45.884249+00:00
1,429
false
Here we are trying every combination , first we are tryong every combination with 2 number .\nFor each combination , we are creating the whole input again and running the dfs and repeat the same process .\n```\nclass Solution {\n public boolean judgePoint24(int[] cards) {\n List<Double> in=new ArrayList<>();\n \n for(int i : cards){\n in.add((double)i);\n }\n \n return dfs(in);\n }\n \n \n public boolean dfs(List<Double> cards){\n if(cards.size()==1){\n if(Math.abs(cards.get(0)-24.0)<0.001) return true;\n return false;\n }\n \n for(int i=0;i<cards.size();i++){\n for(int j=i+1;j<cards.size();j++){\n List<Double> possibleCombinations=generatePossibleResults(cards.get(i),cards.get(j));\n \n for(double c:possibleCombinations){\n List<Double> next=new ArrayList<>();\n next.add(c);\n \n for(int k=0;k<cards.size();k++){\n if(k!=i && k!=j) next.add(cards.get(k));\n } \n if(dfs(next)) return true;\n } \n \n }\n }\n return false;\n \n }\n\n private List<Double> generatePossibleResults(double a, double b) {\n List<Double> res = new ArrayList<>();\n res.add(a + b);\n res.add(a - b);\n res.add(b - a);\n res.add(a * b);\n res.add(a / b);\n res.add(b / a);\n return res;\n }\n}\n```
7
2
['Depth-First Search', 'Java']
4
24-game
Easy readable javascript solution
easy-readable-javascript-solution-by-raj-869b
\nconst judgePoint24 = function(nums) {\n\t//converting all the integers to decimal numbers.\n nums = nums.map(num => Number(num.toFixed(4)));\n \n\t//Fun
rajinisha001
NORMAL
2020-07-12T21:04:48.887982+00:00
2020-07-12T21:04:48.888034+00:00
787
false
```\nconst judgePoint24 = function(nums) {\n\t//converting all the integers to decimal numbers.\n nums = nums.map(num => Number(num.toFixed(4)));\n \n\t//Function that calculates all possible values after all operations on the numbers passed\n const computeTwoNums = (num1, num2) => {\n return [num1 + num2, num1 - num2, num2 - num1, num1 * num2, num1/num2, num2/num1];\n };\n \n const dfs = (list) => {\n let size = list.length;\n if(size === 1) {\n if(Math.abs(list[0] - 24) < 0.001) return true;\n else return false;\n }\n \n for(let i = 0; i < size; i++) {\n for(let j = i + 1; j < size; j++) {\n let nextRound = [];\n for(let k = 0; k < size; k++) {\n if(k !== i && k !== j) nextRound.push(list[k]);\n }\n for(let val of computeTwoNums(list[i], list[j])) {\n nextRound.push(val);\n if(dfs(nextRound)) return true;\n else nextRound.pop();\n }\n }\n }\n return false;\n };\n \n return dfs(nums);\n};\n```
7
0
['Depth-First Search', 'JavaScript']
0
24-game
Python 3 || 9 lines, dfs || T/S: 37% / 99%
python-3-9-lines-dfs-ts-37-99-by-spauldi-cmy6
\ndiv = lambda x,y: reduce(truediv,(x,y)) if y else inf\nops = (add, sub, mul, div)\n\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n\
Spaulding_
NORMAL
2023-07-11T20:06:28.178083+00:00
2024-05-29T17:27:53.588818+00:00
1,080
false
```\ndiv = lambda x,y: reduce(truediv,(x,y)) if y else inf\nops = (add, sub, mul, div)\n\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n\n def dfs(c: list) -> bool:\n\n if len(c) <2 : return isclose(c[0], 24)\n \n for p in set(permutations(c)):\n for num in {reduce(op,p[:2]) for op in ops}:\n if dfs([num] + list(p[2:])): return True\n\n return False \n \n return dfs(cards)\n```\n[https://leetcode.com/problems/24-game/submissions/992130414/](https://leetcode.com/problems/24-game/submissions/992130414/)\n\n\n\nI could be wrong, but I think that time complexity is *O*(1) and space complexity is *O*(1). (The time and space will improve with fewer distinct digits in cards.)
6
0
['Python3']
0
24-game
679: Solution with step by step explanation
679-solution-with-step-by-step-explanati-8usi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Define a helper function called "generate" that takes in two float val
Marlen09
NORMAL
2023-03-20T06:55:22.037368+00:00
2023-03-20T06:55:22.037407+00:00
1,563
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a helper function called "generate" that takes in two float values "a" and "b" and returns a list of float values that represent all possible arithmetic combinations of "a" and "b".\n2. Define another helper function called "dfs" that takes in a list of float values "nums" and returns a boolean value.\n3. In the "dfs" function, check if the length of the input list is equal to 1. If it is, return True if the absolute difference between the first element in the list and 24.0 is less than 0.001, else return False.\n4. Iterate through all possible pairs of indices in the input list using two nested loops.\n5. For each pair of indices, call the "generate" function to get a list of all possible arithmetic combinations of the values at the two indices.\n6. For each value in the list generated in step 6, create a new list called "nextRound" that contains the value from step 6 and all the other values in the input list except the ones at the indices used in step 5.\n7. Recursively call the "dfs" function with the "nextRound" list as the input.\n8. If the recursive call in step 8 returns True, return True in the current call, else continue with the loop in step 5.\n9. If none of the recursive calls in step 8 returned True, return False after the loops in step 5 have completed.\n10. In the "judgePoint24" function, call the "dfs" function with the input list "nums" and return the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n def generate(a: float, b: float) -> List[float]:\n return [a * b,\n math.inf if b == 0 else a / b,\n math.inf if a == 0 else b / a,\n a + b, a - b, b - a]\n\n def dfs(nums: List[float]) -> bool:\n if len(nums) == 1:\n return abs(nums[0] - 24.0) < 0.001\n\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n for num in generate(nums[i], nums[j]):\n nextRound = [num]\n for k in range(len(nums)):\n if k == i or k == j:\n continue\n nextRound.append(nums[k])\n if dfs(nextRound):\n return True\n\n return False\n\n return dfs(nums)\n```
6
0
['Array', 'Math', 'Backtracking', 'Python', 'Python3']
0
24-game
Python, dfs, backtracking
python-dfs-backtracking-by-jered0910-12j7
\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if not nums:\n return False\n return self.dfs(nums, 4)\n
Jered0910
NORMAL
2021-02-13T00:34:31.922117+00:00
2022-06-13T14:25:59.756427+00:00
1,105
false
```\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if not nums:\n return False\n return self.dfs(nums, 4)\n \n \n def dfs(self, nums, n):\n if n == 1:\n if abs(nums[0] - 24) <= 1E-6 :\n return True\n \n for i in range(0, n):\n for j in range(i + 1, n):\n a, b = nums[i], nums[j]\n nums[j] = nums[n - 1]\n \n for temp in [a + b, a - b, b - a, a * b]:\n nums[i] = temp\n if self.dfs(nums, n - 1):\n return True\n \n if a != 0:\n nums[i] = b / a\n if self.dfs(nums, n - 1):\n return True\n if b != 0:\n nums[i] = a / b\n if self.dfs(nums, n - 1):\n return True\n \n nums[i], nums[j] = a, b \n return False\n```
6
0
['Backtracking', 'Depth-First Search', 'Python']
3
24-game
Python3 straightforward recursive solution Faster than 91%
python3-straightforward-recursive-soluti-4qps
\tclass Solution: \n\t\tdef judgePoint24(self, nums: List[int]) -> bool:\n\t\t\t# recursively \'glue\' 2 numbers as a new number, and try to make 24 with the
baiqiang_leetcode
NORMAL
2020-05-13T11:10:59.484521+00:00
2020-05-13T11:10:59.484556+00:00
354
false
\tclass Solution: \n\t\tdef judgePoint24(self, nums: List[int]) -> bool:\n\t\t\t# recursively \'glue\' 2 numbers as a new number, and try to make 24 with the new nums list\n\t\t\t# at the end, when len(nums) = 1, check if it is 24 (due to division some precision loss should be expected, here set as 1e-8 )\n\n\t\t\t# base case\n\t\t\tif len(nums) == 1:\n\t\t\t\tif abs(nums[0] - 24) < 1e-8: \n\t\t\t\t\treturn True\n\t\t\t\treturn False\n\n\t\t\t# general case\n\t\t\tfor i in range(len(nums)-1):\n\t\t\t\tfor j in range(i+1, len(nums)):\n\t\t\t\t\tcombine2 = []\n\t\t\t\t\tcombine2.append(nums[i] + nums[j])\n\t\t\t\t\tcombine2.append(nums[i] * nums[j])\n\t\t\t\t\tcombine2.append(nums[i] - nums[j])\n\t\t\t\t\tcombine2.append(nums[j] - nums[i])\n\t\t\t\t\tif nums[j]: \n\t\t\t\t\t\tcombine2.append(nums[i]/nums[j])\n\t\t\t\t\tif nums[i]:\n\t\t\t\t\t\tcombine2.append(nums[j]/nums[i])\n\n\t\t\t\t\tfor candi in combine2:\n\t\t\t\t\t\tif self.judgePoint24( [candi] + nums[:i] + nums[i+1:j] + nums[j+1:] ):\n\t\t\t\t\t\t\treturn True\n\n\t\t\treturn False
6
0
[]
1
24-game
Simple python dfs + memorization
simple-python-dfs-memorization-by-roc571-jbfz
added precision check fix\n\n\nclass Solution(object):\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n
roc571
NORMAL
2017-09-17T16:29:26.725000+00:00
2017-09-17T16:29:26.725000+00:00
1,345
false
added precision check fix\n\n```\nclass Solution(object):\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n hs = {}\n return self.helper(nums, hs)\n \n def helper(self, nums, hs):\n #print "debug", nums\n if len(nums) == 1:\n if 23.9 <= nums[0] <= 24.1:\n return True\n else:\n return False\n \n nums = sorted(nums)\n if "".join(str(nums) + ",") in hs:\n return False\n \n for i in range(len(nums) - 1):\n for j in range(i + 1, len(nums)):\n a = nums[i]\n b = nums[j]\n if self.helper(nums[:i] + nums[i + 1:j] + nums[j + 1:] + [a + b], hs) == True:\n return True\n if self.helper(nums[:i] + nums[i + 1:j] + nums[j + 1:] + [a * b], hs) == True:\n return True\n if b != 0 and self.helper(nums[:i] + nums[i + 1:j] + nums[j + 1:] + [float(a) / b], hs) == True:\n return True\n if self.helper(nums[:i] + nums[i + 1:j] + nums[j + 1:] + [a - b], hs) == True:\n return True\n if a != 0 and self.helper(nums[:i] + nums[i + 1:j] + nums[j + 1:] + [float(b) / a], hs) == True:\n return True\n if self.helper(nums[:i] + nums[i + 1:j] + nums[j + 1:] + [b - a], hs) == True:\n return True\n \n hs["".join(str(nums) + ",")] = True\n return False\n```
6
0
[]
1
24-game
Numerical Error when doing division for Case [3, 3, 8, 8]
numerical-error-when-doing-division-for-30wj0
I am just trying to figure out a naive solution before I optimize the algorithm. \n\nIt seems that I ran into numerical issue in Case [3,3,8,8]. I tried to debu
linger_baruch
NORMAL
2017-10-16T20:27:34.100000+00:00
2018-08-30T14:58:46.383149+00:00
695
false
I am just trying to figure out a naive solution before I optimize the algorithm. \n\nIt seems that I ran into numerical issue in Case [3,3,8,8]. I tried to debug and it seems it calculates 8/3 as 2.6666666666666665, which in turn gives some number very close to 24.0 but not exact for 8 / (3 - 8 / 3). What should I do in general to handle this kind of situation? \n\n```\nclass Solution(object):\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n return 24.0 in self.Possible_All_Perm(nums)\n \n def Possible_All(self, nums):\n if len(nums) == 1:\n return [float(nums[0])]\n result_temp = set()\n for i in range(len(nums)-1):\n list1 = self.Possible_All(nums[:i+1])\n list2 = self.Possible_All(nums[i+1:])\n result_temp.update(set([i + j for i in list1 for j in list2]))\n result_temp.update(set([i * j for i in list1 for j in list2]))\n result_temp.update(set([i - j for i in list1 for j in list2]))\n result_temp.update(set([i / j for i in list1 for j in list2 if j != 0.]))\n print(nums, result_temp)\n return list(result_temp)\n \n def Possible_All_Perm(self, nums):\n result = set()\n for i in itertools.permutations(nums):\n result.update(self.Possible_All(i))\n return list(result)\n```
6
0
[]
1
24-game
recursion, backtraking, all possible iterations easy explained
recursion-backtraking-all-possible-itera-fkwb
Intuition\nwe will select two pair of elemets and perform all given mathematical operations on that pair and then we store them in in a vector and puch the re
ranaujjawal692
NORMAL
2023-08-26T11:04:18.527975+00:00
2023-08-26T11:04:18.527996+00:00
760
false
# Intuition\nwe will select two pair of elemets and perform all given mathematical operations on that pair and then we store them in in a vector and puch the result of each operation step by step by pushing them into a newly created vector with consists the calculated result and all no\'s except pair whose result is pushed into the vector\n\n# Approach\nwe run for loop nested i,j and k we take i,j to as a pair each time to calculate the result we push it into the nelwy created list and the we again check it condition satisfies \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n^3 * n!*(n-1)! * 3^(n-1))\nn^3 for 3 for loop\nn!*(n-1)!*3^(n-1) for recurssion call\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n^2)\n\n# Code\n```\nclass Solution {\npublic:\nvector<double>fill(double a,double b){\n// all operations\n vector<double>v={a+b,a-b,b-a,a*b};\n if(a!=0) v.push_back(b/a);\n if(b!=0) v.push_back(a/b);\n \n return v;\n}\nbool check(vector<double>&newl){\n if(newl.size()==1){\n // We have only one number left, check if it is approximately 24.\n// will have only one element after appling operations \nreturn abs(newl[0]-24)<=0.1;\n// <=0.1 is for upto 1 decimal places for approximation\n }\n for(int i=0;i<newl.size();i++){\n for(int j=i+1;j<newl.size();j++){\n vector<double> newList;\n for (int k = 0; k < newl.size(); k++) {\n// pushing every element except i , j as we pus operation result of i,j\n if (k != j && k != i) {\n newList.push_back(newl[k]);\n }\n }\n \n \n vector<double>res;\n// new vector to store all possible obtained result\n res=fill(newl[i],newl[j]);\n for(int l=0;l<res.size();l++){\n// push one operation\n newList.push_back(res[l]);\n// check if the array is meeting requirement\n if(check(newList)) return true;\n// if not pop last push\n newList.pop_back();\n }\n }}\n return false;\n}\n bool judgePoint24(vector<int>& cards) {\n vector<double> newl(cards.begin(), cards.end());\n return check(newl);\n }\n};\n```
5
0
['C++']
1
24-game
C++ Solution. Very concise and simple code. (much conciser than most)
c-solution-very-concise-and-simple-code-22w8g
C++\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n vector<double> tmp(nums.begin(), nums.end());\n return dfs(tmp);\n
doub7e
NORMAL
2020-01-06T08:45:56.377639+00:00
2020-01-06T08:45:56.377690+00:00
533
false
```C++\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n vector<double> tmp(nums.begin(), nums.end());\n return dfs(tmp);\n }\nprivate:\n bool dfs(vector<double>& nums){\n if(nums.size() == 1) return fabs(nums[0] - 24) < 1e-8;\n for(int i = 0; i + 1 < nums.size(); ++i){\n for(int j = i + 1; j < nums.size(); ++j){\n vector<double> tmp;\n for(int k = 0; k < nums.size(); ++k)\n if(k != i && k != j) tmp.push_back(nums[k]);\n tmp.push_back(nums[i] + nums[j]);\n if(dfs(tmp)) return true;\n tmp.back() = nums[i] * nums[j];\n if(dfs(tmp)) return true;\n tmp.back() = nums[i] - nums[j];\n if(dfs(tmp)) return true;\n tmp.back() = nums[i] / nums[j];\n if(dfs(tmp)) return true;\n tmp.back() = nums[j] - nums[i];\n if(dfs(tmp)) return true;\n tmp.back() = nums[j] / nums[i];\n if(dfs(tmp)) return true;\n }\n }\n return false;\n }\n};\n```
5
0
[]
0
24-game
C++ solution, Short, Easy to understand
c-solution-short-easy-to-understand-by-m-uv2d
\nclass Solution {\npublic:\n bool f(vector<double> &s){\n if(s.size() == 1) return abs(s[0]-24)<pow(10, -2);\n for(int i=0; i<s.size()-1; i++)
MrGamer2801
NORMAL
2023-07-08T20:22:14.531471+00:00
2023-07-08T20:22:14.531488+00:00
349
false
```\nclass Solution {\npublic:\n bool f(vector<double> &s){\n if(s.size() == 1) return abs(s[0]-24)<pow(10, -2);\n for(int i=0; i<s.size()-1; i++)\n {\n for(int j=0; j<4; j++)\n {\n double a;\n if(j==0) a = s[i]+s[i+1];\n else if(j==1) a = s[i]-s[i+1];\n else if(j==2) a = s[i]*s[i+1];\n else a = s[i]/s[i+1];\n vector<double> t;\n for(int k=0; k<s.size(); k++)\n {\n if(k!=i && k!=i+1) t.push_back(s[k]);\n else if(k==i) t.push_back(a);\n }\n if(f(t)) return true;\n }\n }\n return false;\n }\n\n bool pmt(vector<double> &s, vector<double> &num, int pos, int set){\n if(pos==4) return f(num);\n for(int i=0; i<4; i++)\n {\n if(set&(1<<i)) continue;\n num[pos] = s[i];\n if(pmt(s, num, pos+1, set|(1<<i))) return true;\n }\n return false;\n }\n\n bool judgePoint24(vector<int>& cards) {\n vector<double> s(4), num(4);\n for(int i=0; i<4; i++) s[i] = cards[i];\n return pmt(s, num, 0, 0);\n }\n};\n```
4
0
['Depth-First Search', 'C++']
0
24-game
Easy to understand (with comments) Backtracking > 90% [C++]
easy-to-understand-with-comments-backtra-2l3l
\nclass Solution {\n bool found;\n vector<double> nums;\n char ops[4] = {\'+\', \'-\', \'*\', \'/\'};\n const double eps = 1e-9;\n \npublic:\n
MohammadOTaha
NORMAL
2022-04-12T23:10:58.328135+00:00
2022-04-12T23:14:16.866303+00:00
700
false
```\nclass Solution {\n bool found;\n vector<double> nums;\n char ops[4] = {\'+\', \'-\', \'*\', \'/\'};\n const double eps = 1e-9;\n \npublic:\n double calc(double x, double y, char op) {\n if (op == \'+\') return x + y;\n else if (op == \'-\') return x - y;\n else if (op == \'*\') return x * y;\n else return x / y;\n }\n \n vector<double> getEvaluations(int l, int r) {\n if (found) return {}; // If an evaluation == 24 been already found, no need to continue\n if (l == r) return {nums[l]}; // As if we put parentheses around a single number, so its evalution is the number itself\n\n vector<double> ret;\n // Trying all the ways we could split the current range into two subranges\n // for example: if cards = {1,2,3,4} & l = 1, r = 3\n // all the possible splits are: {(2), (3,4)}, {(2,3), (4)}\n for (int i = l; i < r; i++) { \n // get all possiple evaluations from left & right subranges \n auto resL = getEvaluations(l, i), resR = getEvaluations(i+1, r);\n\n // getting all possilbe evaluations by using an operation between left & right subranges\n for (auto x : resL){\n for (auto y : resR) {\n for (char op : ops) {\n if (op == \'/\' && y == 0) continue; // avoid dividing by 0\n \n ret.push_back(calc(x, y, op));\n \n // checking if the whole range evaluation resulted to 24\n // because we could get 24 in a sub range but it can\'t be an answer\n if (l == 0 && r == 3) found |= (abs(ret.back() - 24.0) < eps);\n }\n }\n }\n }\n\n return ret;\n }\n\n bool judgePoint24(vector<int>& cards) {\n for (auto x : cards) nums.push_back(x * 1.0); // converting to double, for better precision\n\t\t\n sort(nums.begin(), nums.end());\n do {\n found = false;\n getEvaluations(0, 3);\n if (found) return true;\n } while (next_permutation(nums.begin(), nums.end()));\n\n return false;\n }\n};\n```
4
0
['Backtracking', 'C']
0
24-game
C++ - Easy beats 100% of solutions [0 ms]
c-easy-beats-100-of-solutions-0-ms-by-dh-5hed
There are only 5 possible ways of adding brackets to an expression of length 4.\n\nLets\' say the expression nums = { a , b, c , d}. The only possible sequence
dheer1206
NORMAL
2021-02-27T10:00:37.506160+00:00
2021-02-27T10:21:18.302620+00:00
563
false
There are only 5 possible ways of adding brackets to an expression of length 4.\n\nLets\' say the expression nums = { a , b, c , d}. The only possible sequence of brackets is:\nHere **op** represent any operation in the set { + , - , / , * }\n1. (a op1 b) op2 (c op3 d)\n2. ((a op1 b) op2 c) op3 d\n3. a op1 (b op2 c) op3 d\n4. a op1 ((b op2 c) op3 d)\n5. a op1 (b op2 (c op3 d))\n\nFor every possible sequence of brackets (from above mentioned 5), we need to choose the values, op1, op2 and op3. Each of which belongs to set { +, -, /, * }.\nTherefore, Possibilities for each possible sequence = 4 * 4 * 4 = 64\nWe have 5 possible sequences, there total possibilities = 5 * 64 = 320\n\nNow, we have 320 possible outputs for one nums sequence of the form {a, b, c, d}.\n\nIn the given question, it is also mentioned that we can choose the given numbers in any possible combination. Therefore, we have to consider all possible permutations:\nFor eg: Given nums = {1,3,4,6} \nWe can also use numbers in a different order like 6 / ( 1 - 3 / 4 ).\n\nSince the sequence is of size 4, there can be 24 possible permutations.\nTherefore total possibilites = 24 * 320 = 7680\n\n\n```\n\n\nclass Solution {\npublic:\n \n char ops[4] = {\'*\',\'/\',\'+\',\'-\'};\n vector<string> poss;\n const double INF = 1e-9;\n \n double process(double num1, double num2, char sym) {\n switch (sym) {\n case \'+\':\n return num1+num2;\n case \'-\':\n return num1-num2;\n case \'*\':\n return num1*num2;\n case \'/\':\n return num1/num2;\n }\n \n return 0;\n }\n \n bool way1(vector<vector<int>>& numss) {\n double temp1, temp2, temp3;\n for (auto nums: numss) {\n for (int i=0;i<4;i++) {\n for (int j=0;j<4;j++) {\n for (int k=0;k<4;k++) {\n \n // Way1 --> (nums[0] opI nums[1]) opJ (num[2] opK nums[3])\n \n temp1 = process(nums[0], nums[1], ops[i]);\n temp2 = process(nums[2], nums[3], ops[j]);\n temp3 = process(temp1, temp2, ops[k]);\n //cout<<"way1 --"<<ops[i]<<" "<<ops[j]<<" "<<ops[k]<<" "<<temp1<<" "<<temp2<<" "<<temp3<<"\\n";\n if (fabs(24-temp3) < INF)\n return true;\n }\n }\n }\n }\n return false;\n }\n \n bool way2(vector<vector<int>>& numss) {\n double temp1, temp2, temp3;\n for (auto nums: numss) {\n for (int i=0;i<4;i++) {\n for (int j=0;j<4;j++) {\n for (int k=0;k<4;k++) {\n \n // Way2 --> ((nums[0] opI nums[1]) opJ num[2]) opK nums[3]\n \n temp1 = process(nums[0], nums[1], ops[i]);\n temp2 = process(temp1, nums[2], ops[j]);\n temp3 = process(temp2, nums[3], ops[k]);\n if (fabs(24-temp3) < INF)\n return true;\n }\n }\n }\n }\n return false;\n }\n \n bool way3(vector<vector<int>>& numss) {\n double temp1, temp2, temp3;\n for (auto nums: numss) {\n for (int i=0;i<4;i++) {\n for (int j=0;j<4;j++) {\n for (int k=0;k<4;k++) {\n \n // Way3 --> nums[0] opJ (nums[1] opI num[2]) opK nums[3]\n \n temp1 = process(nums[1], nums[2], ops[i]);\n temp2 = process(nums[0], temp1, ops[j]);\n temp3 = process(temp2, nums[3], ops[k]);\n if (fabs(24-temp3) < INF)\n return true;\n }\n }\n }\n }\n return false;\n }\n \n bool way4(vector<vector<int>>& numss) {\n double temp1, temp2, temp3;\n for (auto nums: numss) {\n for (int i=0;i<4;i++) {\n for (int j=0;j<4;j++) {\n for (int k=0;k<4;k++) {\n \n // Way4 --> nums[0] opK ((nums[1] opI num[2]) opJ nums[3])\n \n temp1 = process(nums[1], nums[2], ops[i]);\n temp2 = process(temp1, nums[3], ops[j]);\n temp3 = process(nums[0], temp2, ops[k]);\n if (fabs(24-temp3) < INF)\n return true;\n }\n }\n }\n }\n return false;\n }\n \n bool way5(vector<vector<int>>& numss) {\n double temp1, temp2, temp3;\n for (auto nums: numss) {\n for (int i=0;i<4;i++) {\n for (int j=0;j<4;j++) {\n for (int k=0;k<4;k++) {\n \n // Way5 --> nums[0] opK (nums[1] opJ (num[2] opI nums[3]))\n \n temp1 = process(nums[2], nums[3], ops[i]);\n temp2 = process(nums[1], temp1, ops[j]);\n temp3 = process(nums[0], temp2, ops[k]);\n if (fabs(24-temp3) < INF)\n return true;\n }\n }\n }\n }\n return false;\n }\n \n bool judgePoint24(vector<int>& nums) {\n \n vector<vector<int>> numss;\n sort(nums.begin(), nums.end());\n do {\n numss.push_back(nums);\n \n } while (next_permutation(nums.begin(), nums.end()));\n \n return way1(numss) || way2(numss) || way3(numss) || way4(numss) || way5(numss);\n }\n};\n```
4
0
[]
2
24-game
Python3 solution with eval()
python3-solution-with-eval-by-todor91-k3oi
Here I just simulate all permutations of numbers and operators and use the builtin eval() function to get the result. There are 6 different cases for parenthese
todor91
NORMAL
2020-05-22T11:37:56.052243+00:00
2020-05-22T12:07:20.292383+00:00
210
false
Here I just simulate all permutations of numbers and operators and use the builtin eval() function to get the result. There are 6 different cases for parentheses and I iterate through all of them.\n\n```\n def judgePoint24(self, nums: List[int]) -> bool:\n\n @lru_cache(None)\n def solve(a, b, c, d):\n for op1, op2, op3 in itertools.product(\'/*-+\', repeat=3):\n for case in [\n \'{}{}{}{}{}{}{}\', # without parentheses\n \'({}{}{}){}{}{}{}\', # parentheses around a and b\n \'{}{}{}{}({}{}{})\', # parentheses around c and d\n \'({}{}{}{}{}){}{}\', # parentheses around a, b and c\n \'{}{}({}{}{}{}{})\', # parentheses around b, c and d\n \'({}{}{}){}({}{}{})\']: # parentheses around a and b and around c and d\n try:\n if math.isclose(24, eval(case.format(a, op1, b, op2, c, op3, d))):\n return True\n except ZeroDivisionError:\n pass\n\n return any(solve(a, b, c, d) for a, b, c, d in itertools.permutations(nums))\n```
4
0
[]
0
24-game
Java bringing new meaning to brute force
java-bringing-new-meaning-to-brute-force-c97f
\nThis is just an Intellij inline-method refactoring of this other ugly solution: https://leetcode.com/problems/24-game/discuss/584767/Java-no-control-flow-(no-
glxxyz
NORMAL
2020-04-18T05:57:49.705862+00:00
2020-04-18T06:03:52.959694+00:00
593
false
\nThis is just an Intellij inline-method refactoring of this other ugly solution: https://leetcode.com/problems/24-game/discuss/584767/Java-no-control-flow-(no-if-for-while-etc.)-beats-100-time-100-space\n\nFor some reason it\'s much slower and uses much more memory than the version with method calls. Maybe someone who knows more about Java than me can explain why the massive boolean OR expression is slower than method calls. \n\nI would have done more refactoring to take this to its logical conclusion but it got too big for Leetcode so I left it here.\n\n```\n/*\n\nRuntime: 7 ms, faster than 18.69% of Java online submissions for 24 Game.\nMemory Usage: 64.5 MB, less than 6.25% of Java online submissions for 24 Game.\n\n*/\n\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n\n double a = Double.valueOf(nums[0]);\n double b = Double.valueOf(nums[1]);\n double c = Double.valueOf(nums[2]);\n double d = Double.valueOf(nums[3]);\n\n return judge(a, b, c, d)\n || judge(a, b, d, c)\n || judge(a, c, b, d)\n || judge(a, c, d, b)\n || judge(a, d, b, c)\n || judge(a, d, c, b) \n || judge(b, a, c, d)\n || judge(b, a, d, c)\n || judge(b, c, a, d)\n || judge(b, c, d, a)\n || judge(b, d, a, c)\n || judge(b, d, c, a) \n || judge(c, a, b, d)\n || judge(c, a, d, b)\n || judge(c, b, a, d)\n || judge(c, b, d, a)\n || judge(c, d, a, b)\n || judge(c, d, b, a) \n || judge(d, a, b, c)\n || judge(d, a, c, b)\n || judge(d, b, a, c)\n || judge(d, b, c, a)\n || judge(d, c, a, b)\n || judge(d, c, b, a);\n }\n\n private boolean judge(double a, double b, double c, double d) {\n\n return judge(a * b * c * d) || judge(a + b * c * d) || judge(a - b * c * d)\n || b * c * d != 0 && judge(a / (b * c * d)) || judge(a * (b + c * d))\n || judge(a + b + c * d) || judge(a - (b + c * d))\n || b + c * d != 0 && judge(a / (b + c * d)) || judge(a * (b - c * d))\n || judge(a + b - c * d) || judge(a - (b - c * d))\n || b - c * d != 0 && judge(a / (b - c * d))\n || c * d != 0 && (judge(a * (b / (c * d))) || judge(a + b / (c * d))\n || judge(a - b / (c * d)) || b / (c * d) != 0 && judge(a / (b / (c * d))))\n || judge(a * c * d * b) || judge(a + c * d * b)\n || judge(a - c * d * b) || c * d * b != 0 && judge(a / (c * d * b))\n || judge(a * (c * d + b)) || judge(a + c * d + b)\n || judge(a - (c * d + b)) || c * d + b != 0 && judge(a / (c * d + b))\n || judge(a * (c * d - b)) || judge(a + c * d - b)\n || judge(a - (c * d - b)) || c * d - b != 0 && judge(a / (c * d - b))\n || b != 0 && (judge(a * (c * d / b)) || judge(a + c * d / b)\n || judge(a - c * d / b) || c * d / b != 0 && judge(a / (c * d / b)))\n || judge(b * a * c * d) || judge(b + a * c * d)\n || judge(b - a * c * d) || a * c * d != 0 && judge(b / (a * c * d))\n || judge(b * (a + c * d)) || judge(b + a + c * d)\n || judge(b - (a + c * d)) || a + c * d != 0 && judge(b / (a + c * d))\n || judge(b * (a - c * d)) || judge(b + a - c * d)\n || judge(b - (a - c * d)) || a - c * d != 0 && judge(b / (a - c * d))\n || c * d != 0 && (judge(b * (a / (c * d))) || judge(b + a / (c * d))\n || judge(b - a / (c * d)) || a / (c * d) != 0 && judge(b / (a / (c * d))))\n || judge(b * c * d * a) || judge(b + c * d * a)\n || judge(b - c * d * a) || c * d * a != 0 && judge(b / (c * d * a))\n || judge(b * (c * d + a)) || judge(b + c * d + a)\n || judge(b - (c * d + a)) || c * d + a != 0 && judge(b / (c * d + a))\n || judge(b * (c * d - a)) || judge(b + c * d - a)\n || judge(b - (c * d - a)) || c * d - a != 0 && judge(b / (c * d - a))\n || a != 0 && (judge(b * (c * d / a)) || judge(b + c * d / a)\n || judge(b - c * d / a) || c * d / a != 0 && judge(b / (c * d / a)))\n || judge(c * d * a * b) || judge(c * d + a * b)\n || judge(c * d - a * b) || a * b != 0 && judge(c * d / (a * b))\n || judge(c * d * (a + b)) || judge(c * d + a + b)\n || judge(c * d - (a + b)) || a + b != 0 && judge(c * d / (a + b))\n || judge(c * d * (a - b)) || judge(c * d + a - b)\n || judge(c * d - (a - b)) || a - b != 0 && judge(c * d / (a - b))\n || b != 0 && (judge(c * d * (a / b)) || judge(c * d + a / b)\n || judge(c * d - a / b) || a / b != 0 && judge(c * d / (a / b)))\n || judge(c * d * b * a) || judge(c * d + b * a)\n || judge(c * d - b * a) || b * a != 0 && judge(c * d / (b * a))\n || judge(c * d * (b + a)) || judge(c * d + b + a)\n || judge(c * d - (b + a)) || b + a != 0 && judge(c * d / (b + a))\n || judge(c * d * (b - a)) || judge(c * d + b - a)\n || judge(c * d - (b - a)) || b - a != 0 && judge(c * d / (b - a))\n || a != 0 && (judge(c * d * (b / a)) || judge(c * d + b / a)\n || judge(c * d - b / a) || b / a != 0 && judge(c * d / (b / a)))\n || judge(a * b * (c + d)) || judge(a + b * (c + d))\n || judge(a - b * (c + d)) || b * (c + d) != 0 && judge(a / (b * (c + d)))\n || judge(a * (b + c + d)) || judge(a + b + c + d)\n || judge(a - (b + c + d)) || b + c + d != 0 && judge(a / (b + c + d))\n || judge(a * (b - (c + d))) || judge(a + b - (c + d))\n || judge(a - (b - (c + d))) || b - (c + d) != 0 && judge(a / (b - (c + d)))\n || c + d != 0 && (judge(a * (b / (c + d))) || judge(a + b / (c + d))\n || judge(a - b / (c + d)) || b / (c + d) != 0 && judge(a / (b / (c + d))))\n || judge(a * (c + d) * b) || judge(a + (c + d) * b)\n || judge(a - (c + d) * b) || (c + d) * b != 0 && judge(a / ((c + d) * b))\n || judge(a * (c + d + b)) || judge(a + c + d + b)\n || judge(a - (c + d + b)) || c + d + b != 0 && judge(a / (c + d + b))\n || judge(a * (c + d - b)) || judge(a + c + d - b)\n || judge(a - (c + d - b)) || c + d - b != 0 && judge(a / (c + d - b)) || b != 0 && (\n judge(a * ((c + d) / b)) || judge(a + (c + d) / b)\n || judge(a - (c + d) / b) || (c + d) / b != 0 && judge(a / ((c + d) / b)))\n || judge(b * a * (c + d)) || judge(b + a * (c + d))\n || judge(b - a * (c + d)) || a * (c + d) != 0 && judge(b / (a * (c + d)))\n || judge(b * (a + c + d)) || judge(b + a + c + d)\n || judge(b - (a + c + d)) || a + c + d != 0 && judge(b / (a + c + d))\n || judge(b * (a - (c + d))) || judge(b + a - (c + d))\n || judge(b - (a - (c + d))) || a - (c + d) != 0 && judge(b / (a - (c + d)))\n || c + d != 0 && (judge(b * (a / (c + d))) || judge(b + a / (c + d))\n || judge(b - a / (c + d)) || a / (c + d) != 0 && judge(b / (a / (c + d))))\n || judge(b * (c + d) * a) || judge(b + (c + d) * a)\n || judge(b - (c + d) * a) || (c + d) * a != 0 && judge(b / ((c + d) * a))\n || judge(b * (c + d + a)) || judge(b + c + d + a)\n || judge(b - (c + d + a)) || c + d + a != 0 && judge(b / (c + d + a))\n || judge(b * (c + d - a)) || judge(b + c + d - a)\n || judge(b - (c + d - a)) || c + d - a != 0 && judge(b / (c + d - a)) || a != 0 && (\n judge(b * ((c + d) / a)) || judge(b + (c + d) / a)\n || judge(b - (c + d) / a) || (c + d) / a != 0 && judge(b / ((c + d) / a)))\n || judge((c + d) * a * b) || judge(c + d + a * b)\n || judge((c + d) - a * b) || a * b != 0 && judge((c + d) / (a * b))\n || judge((c + d) * (a + b)) || judge(c + d + a + b)\n || judge((c + d) - (a + b)) || a + b != 0 && judge((c + d) / (a + b))\n || judge((c + d) * (a - b)) || judge(c + d + a - b)\n || judge((c + d) - (a - b)) || a - b != 0 && judge((c + d) / (a - b)) || b != 0 && (\n judge((c + d) * (a / b)) || judge(c + d + a / b)\n || judge((c + d) - a / b) || a / b != 0 && judge((c + d) / (a / b)))\n || judge((c + d) * b * a) || judge(c + d + b * a)\n || judge((c + d) - b * a) || b * a != 0 && judge((c + d) / (b * a))\n || judge((c + d) * (b + a)) || judge(c + d + b + a)\n || judge((c + d) - (b + a)) || b + a != 0 && judge((c + d) / (b + a))\n || judge((c + d) * (b - a)) || judge(c + d + b - a)\n || judge((c + d) - (b - a)) || b - a != 0 && judge((c + d) / (b - a)) || a != 0 && (\n judge((c + d) * (b / a)) || judge(c + d + b / a)\n || judge((c + d) - b / a) || b / a != 0 && judge((c + d) / (b / a)))\n || judge(a * b * (c - d)) || judge(a + b * (c - d))\n || judge(a - b * (c - d)) || b * (c - d) != 0 && judge(a / (b * (c - d)))\n || judge(a * (b + c - d)) || judge(a + b + c - d)\n || judge(a - (b + c - d)) || b + c - d != 0 && judge(a / (b + c - d))\n || judge(a * (b - (c - d))) || judge(a + b - (c - d))\n || judge(a - (b - (c - d))) || b - (c - d) != 0 && judge(a / (b - (c - d)))\n || c - d != 0 && (judge(a * (b / (c - d))) || judge(a + b / (c - d))\n || judge(a - b / (c - d)) || b / (c - d) != 0 && judge(a / (b / (c - d))))\n || judge(a * (c - d) * b) || judge(a + (c - d) * b)\n || judge(a - (c - d) * b) || (c - d) * b != 0 && judge(a / ((c - d) * b))\n || judge(a * (c - d + b)) || judge(a + c - d + b)\n || judge(a - (c - d + b)) || c - d + b != 0 && judge(a / (c - d + b))\n || judge(a * (c - d - b)) || judge(a + c - d - b)\n || judge(a - (c - d - b)) || c - d - b != 0 && judge(a / (c - d - b)) || b != 0 && (\n judge(a * ((c - d) / b)) || judge(a + (c - d) / b)\n || judge(a - (c - d) / b) || (c - d) / b != 0 && judge(a / ((c - d) / b)))\n || judge(b * a * (c - d)) || judge(b + a * (c - d))\n || judge(b - a * (c - d)) || a * (c - d) != 0 && judge(b / (a * (c - d)))\n || judge(b * (a + c - d)) || judge(b + a + c - d)\n || judge(b - (a + c - d)) || a + c - d != 0 && judge(b / (a + c - d))\n || judge(b * (a - (c - d))) || judge(b + a - (c - d))\n || judge(b - (a - (c - d))) || a - (c - d) != 0 && judge(b / (a - (c - d)))\n || c - d != 0 && (judge(b * (a / (c - d))) || judge(b + a / (c - d))\n || judge(b - a / (c - d)) || a / (c - d) != 0 && judge(b / (a / (c - d))))\n || judge(b * (c - d) * a) || judge(b + (c - d) * a)\n || judge(b - (c - d) * a) || (c - d) * a != 0 && judge(b / ((c - d) * a))\n || judge(b * (c - d + a)) || judge(b + c - d + a)\n || judge(b - (c - d + a)) || c - d + a != 0 && judge(b / (c - d + a))\n || judge(b * (c - d - a)) || judge(b + c - d - a)\n || judge(b - (c - d - a)) || c - d - a != 0 && judge(b / (c - d - a)) || a != 0 && (\n judge(b * ((c - d) / a)) || judge(b + (c - d) / a)\n || judge(b - (c - d) / a) || (c - d) / a != 0 && judge(b / ((c - d) / a)))\n || judge((c - d) * a * b) || judge(c - d + a * b)\n || judge((c - d) - a * b) || a * b != 0 && judge((c - d) / (a * b))\n || judge((c - d) * (a + b)) || judge(c - d + a + b)\n || judge((c - d) - (a + b)) || a + b != 0 && judge((c - d) / (a + b))\n || judge((c - d) * (a - b)) || judge(c - d + a - b)\n || judge((c - d) - (a - b)) || a - b != 0 && judge((c - d) / (a - b)) || b != 0 && (\n judge((c - d) * (a / b)) || judge(c - d + a / b)\n || judge((c - d) - a / b) || a / b != 0 && judge((c - d) / (a / b)))\n || judge((c - d) * b * a) || judge(c - d + b * a)\n || judge((c - d) - b * a) || b * a != 0 && judge((c - d) / (b * a))\n || judge((c - d) * (b + a)) || judge(c - d + b + a)\n || judge((c - d) - (b + a)) || b + a != 0 && judge((c - d) / (b + a))\n || judge((c - d) * (b - a)) || judge(c - d + b - a)\n || judge((c - d) - (b - a)) || b - a != 0 && judge((c - d) / (b - a)) || a != 0 && (\n judge((c - d) * (b / a)) || judge(c - d + b / a)\n || judge((c - d) - b / a) || b / a != 0 && judge((c - d) / (b / a)))\n || d != 0 && (judge(a * b * (c / d)) || judge(a + b * (c / d))\n || judge(a - b * (c / d)) || b * (c / d) != 0 && judge(a / (b * (c / d)))\n || judge(a * (b + c / d)) || judge(a + b + c / d)\n || judge(a - (b + c / d)) || b + c / d != 0 && judge(a / (b + c / d))\n || judge(a * (b - c / d)) || judge(a + b - c / d)\n || judge(a - (b - c / d)) || b - c / d != 0 && judge(a / (b - c / d))\n || c / d != 0 && (judge(a * (b / (c / d))) || judge(a + b / (c / d))\n || judge(a - b / (c / d)) || b / (c / d) != 0 && judge(a / (b / (c / d))))\n || judge(a * (c / d) * b) || judge(a + c / d * b)\n || judge(a - c / d * b) || c / d * b != 0 && judge(a / (c / d * b))\n || judge(a * (c / d + b)) || judge(a + c / d + b)\n || judge(a - (c / d + b)) || c / d + b != 0 && judge(a / (c / d + b))\n || judge(a * (c / d - b)) || judge(a + c / d - b)\n || judge(a - (c / d - b)) || c / d - b != 0 && judge(a / (c / d - b)) || b != 0 && (\n judge(a * (c / d / b)) || judge(a + c / d / b)\n || judge(a - c / d / b) || c / d / b != 0 && judge(a / (c / d / b)))\n || judge(b * a * (c / d)) || judge(b + a * (c / d))\n || judge(b - a * (c / d)) || a * (c / d) != 0 && judge(b / (a * (c / d)))\n || judge(b * (a + c / d)) || judge(b + a + c / d)\n || judge(b - (a + c / d)) || a + c / d != 0 && judge(b / (a + c / d))\n || judge(b * (a - c / d)) || judge(b + a - c / d)\n || judge(b - (a - c / d)) || a - c / d != 0 && judge(b / (a - c / d))\n || c / d != 0 && (judge(b * (a / (c / d))) || judge(b + a / (c / d))\n || judge(b - a / (c / d)) || a / (c / d) != 0 && judge(b / (a / (c / d))))\n || judge(b * (c / d) * a) || judge(b + c / d * a)\n || judge(b - c / d * a) || c / d * a != 0 && judge(b / (c / d * a))\n || judge(b * (c / d + a)) || judge(b + c / d + a)\n || judge(b - (c / d + a)) || c / d + a != 0 && judge(b / (c / d + a))\n || judge(b * (c / d - a)) || judge(b + c / d - a)\n || judge(b - (c / d - a)) || c / d - a != 0 && judge(b / (c / d - a)) || a != 0 && (\n judge(b * (c / d / a)) || judge(b + c / d / a)\n || judge(b - c / d / a) || c / d / a != 0 && judge(b / (c / d / a)))\n || judge((c / d) * a * b) || judge(c / d + a * b)\n || judge(c / d - a * b) || a * b != 0 && judge(c / d / (a * b))\n || judge(c / d * (a + b)) || judge(c / d + a + b)\n || judge(c / d - (a + b)) || a + b != 0 && judge(c / d / (a + b))\n || judge(c / d * (a - b)) || judge(c / d + a - b)\n || judge(c / d - (a - b)) || a - b != 0 && judge(c / d / (a - b)) || b != 0 && (\n judge(c / d * (a / b)) || judge(c / d + a / b)\n || judge(c / d - a / b) || a / b != 0 && judge(c / d / (a / b)))\n || judge((c / d) * b * a) || judge(c / d + b * a)\n || judge(c / d - b * a) || b * a != 0 && judge(c / d / (b * a))\n || judge(c / d * (b + a)) || judge(c / d + b + a)\n || judge(c / d - (b + a)) || b + a != 0 && judge(c / d / (b + a))\n || judge(c / d * (b - a)) || judge(c / d + b - a)\n || judge(c / d - (b - a)) || b - a != 0 && judge(c / d / (b - a)) || a != 0 && (\n judge(c / d * (b / a)) || judge(c / d + b / a)\n || judge(c / d - b / a) || b / a != 0 && judge(c / d / (b / a))));\n }\n\n private boolean judge(double a) {\n return Math.abs(a - 24) < 0.000001;\n }\n}\n```
4
0
['Java']
3
24-game
Python, Time: O(1)[100.0%], Space: O(1)[100.0%], precalculation, cheat solution
python-time-o11000-space-o11000-precalcu-xu6p
\nBy just list all cases, it can run very fase!!!\nThis kinds of precalculate cheat are common skill to let program even more faster.\nHowever, it still need a
chumicat
NORMAL
2019-11-29T17:50:54.378734+00:00
2019-11-30T07:32:27.285059+00:00
1,205
false
\nBy just list all cases, it can run very fase!!!\nThis kinds of precalculate cheat are common skill to let program even more faster.\nHowever, it still need a right solution to generate all cases.\n(Markdown didn\'t work in result which will let this arcitle a littlle bit messy :p)\n\n====================================================================================================\n\n## 1. Precalculate - True cases\n### There have totally 404 cases\n```python\n# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282501398/\n# (Time, Space) Complexity : O(1), O(1)\n\ncases = {(1, 2, 5, 5), (2, 5, 6, 8), (3, 3, 7, 7), (3, 5, 7, 9), (1, 4, 6, 7), (5, 5, 9, 9), (3, 3, 3, 9), (2, 2, 6, 6), (2, 4, 6, 8), (1, 5, 5, 6), (3, 4, 4, 7), (1, 3, 8, 9), (1, 2, 4, 8), (4, 8, 8, 8), (2, 2, 2, 8), (3, 6, 6, 8), (1, 2, 5, 9), (5, 6, 7, 9), (1, 7, 7, 9), (2, 3, 4, 4), (2, 2, 5, 9), (1, 3, 4, 7), (2, 3, 5, 5), (3, 3, 3, 4), (2, 5, 5, 7), (1, 6, 6, 9), (4, 6, 7, 9), (1, 3, 5, 8), (5, 5, 5, 6), (5, 5, 8, 8), (2, 5, 8, 8), (3, 5, 6, 7), (2, 2, 2, 3), (3, 5, 7, 8), (1, 4, 6, 6), (2, 3, 4, 8), (2, 4, 5, 6), (2, 3, 5, 9), (2, 4, 6, 7), (1, 5, 5, 5), (1, 6, 9, 9), (1, 3, 8, 8), (1, 2, 4, 7), (3, 4, 7, 8), (3, 3, 6, 9), (3, 6, 6, 7), (6, 6, 7, 9), (4, 4, 5, 5), (2, 2, 4, 7), (4, 5, 9, 9), (1, 2, 7, 8), (1, 4, 5, 5), (4, 6, 6, 7), (2, 2, 5, 8), (1, 3, 4, 6), (1, 1, 4, 7), (1, 2, 8, 9), (3, 7, 7, 9), (1, 6, 6, 8), (4, 6, 7, 8), (1, 3, 5, 7), (1, 1, 5, 8), (1, 5, 5, 9), (3, 5, 6, 6), (5, 6, 6, 8), (4, 5, 6, 8), (2, 3, 4, 7), (6, 7, 9, 9), (1, 4, 5, 9), (2, 4, 5, 5), (3, 4, 6, 6), (2, 8, 8, 8), (5, 8, 8, 8), (4, 4, 4, 4), (2, 3, 7, 8), (3, 3, 5, 7), (3, 4, 7, 7), (2, 3, 8, 9), (1, 3, 3, 5), (3, 3, 6, 8), (2, 2, 4, 6), (1, 2, 7, 7), (2, 2, 2, 4), (2, 6, 7, 9), (2, 3, 3, 6), (4, 6, 6, 6), (1, 3, 4, 5), (1, 1, 4, 6), (3, 7, 7, 8), (2, 2, 8, 9), (1, 3, 7, 7), (1, 5, 7, 9), (4, 4, 4, 8), (4, 8, 9, 9), (4, 5, 5, 6), (1, 2, 3, 5), (1, 3, 3, 9), (5, 6, 6, 7), (4, 5, 6, 7), (1, 1, 8, 8), (1, 4, 4, 7), (2, 4, 4, 9), (1, 4, 5, 8), (2, 3, 7, 7), (3, 3, 5, 6), (1, 2, 6, 6), (2, 5, 7, 9), (1, 4, 8, 9), (3, 3, 8, 8), (1, 2, 3, 9), (1, 3, 3, 4), (4, 4, 8, 9), (3, 3, 9, 9), (2, 2, 4, 5), (2, 4, 4, 4), (2, 2, 7, 7), (2, 6, 7, 8), (2, 3, 3, 5), (2, 4, 7, 9), (1, 2, 2, 4), (3, 7, 7, 7), (1, 1, 3, 9), (2, 2, 8, 8), (2, 6, 8, 9), (3, 4, 6, 9), (1, 5, 7, 8), (4, 4, 4, 7), (3, 5, 5, 9), (4, 5, 5, 5), (1, 2, 3, 4), (1, 3, 3, 8), (5, 6, 6, 6), (2, 2, 3, 5), (4, 4, 7, 8), (1, 7, 8, 9), (1, 4, 4, 6), (3, 6, 8, 9), (2, 4, 4, 8), (1, 3, 6, 9), (2, 3, 3, 9), (1, 2, 2, 8), (1, 4, 7, 7), (1, 1, 3, 4), (1, 6, 7, 9), (4, 6, 8, 9), (3, 4, 5, 8), (1, 4, 8, 8), (2, 6, 6, 7), (3, 5, 8, 9), (1, 3, 3, 3), (2, 2, 3, 9), (3, 6, 7, 8), (1, 1, 2, 7), (2, 4, 7, 8), (1, 5, 6, 6), (3, 9, 9, 9), (3, 3, 4, 5), (1, 1, 3, 8), (1, 2, 6, 9), (5, 5, 6, 7), (2, 5, 6, 7), (3, 5, 5, 8), (6, 6, 6, 6), (1, 1, 6, 9), (2, 2, 3, 4), (3, 4, 9, 9), (5, 7, 7, 9), (4, 4, 7, 7), (3, 3, 3, 8), (2, 4, 4, 7), (1, 3, 6, 8), (1, 2, 2, 7), (3, 4, 4, 6), (3, 3, 4, 9), (4, 6, 8, 8), (3, 4, 5, 7), (1, 3, 9, 9), (4, 5, 7, 9), (2, 2, 2, 7), (2, 3, 6, 9), (1, 2, 5, 8), (2, 6, 6, 6), (3, 5, 8, 8), (5, 6, 7, 8), (2, 2, 3, 8), (5, 6, 8, 9), (3, 3, 3, 3), (2, 8, 9, 9), (4, 5, 8, 9), (3, 6, 7, 7), (1, 1, 2, 6), (2, 2, 6, 9), (3, 3, 4, 4), (3, 8, 8, 9), (5, 5, 5, 5), (6, 8, 8, 9), (1, 1, 3, 7), (5, 5, 6, 6), (2, 5, 6, 6), (1, 1, 6, 8), (2, 2, 3, 3), (2, 7, 7, 8), (3, 7, 8, 9), (3, 3, 3, 7), (2, 3, 5, 8), (2, 4, 6, 6), (3, 4, 4, 5), (1, 5, 8, 9), (5, 5, 5, 9), (1, 2, 4, 6), (3, 7, 9, 9), (3, 4, 5, 6), (4, 5, 7, 8), (3, 6, 6, 6), (1, 2, 5, 7), (4, 4, 6, 9), (5, 6, 7, 7), (3, 3, 7, 9), (1, 4, 6, 9), (6, 6, 8, 9), (2, 2, 5, 7), (1, 2, 8, 8), (2, 4, 5, 9), (4, 6, 7, 7), (2, 2, 6, 8), (1, 3, 5, 6), (1, 1, 5, 7), (3, 4, 4, 9), (2, 3, 9, 9), (4, 4, 5, 8), (2, 3, 4, 6), (3, 7, 8, 8), (1, 3, 4, 9), (2, 3, 5, 7), (3, 3, 3, 6), (2, 5, 5, 9), (4, 7, 7, 8), (3, 4, 4, 4), (1, 5, 8, 8), (1, 2, 4, 5), (4, 7, 8, 9), (2, 3, 8, 8), (3, 3, 6, 7), (3, 5, 6, 9), (1, 5, 9, 9), (3, 3, 7, 8), (6, 6, 8, 8), (2, 2, 5, 6), (1, 3, 4, 4), (1, 1, 4, 5), (2, 4, 5, 8), (1, 6, 6, 6), (1, 1, 5, 6), (1, 2, 4, 9), (4, 5, 6, 6), (4, 4, 5, 7), (2, 2, 4, 9), (2, 3, 4, 5), (1, 4, 5, 7), (4, 6, 6, 9), (1, 3, 4, 8), (1, 1, 4, 9), (4, 7, 7, 7), (3, 3, 5, 5), (5, 5, 7, 8), (2, 5, 7, 8), (1, 2, 4, 4), (4, 5, 5, 9), (1, 2, 3, 8), (3, 3, 6, 6), (5, 5, 8, 9), (2, 5, 8, 9), (3, 5, 6, 8), (4, 4, 8, 8), (2, 2, 4, 4), (1, 8, 8, 9), (2, 3, 4, 9), (1, 1, 1, 8), (2, 2, 5, 5), (1, 1, 4, 4), (2, 4, 5, 7), (2, 6, 8, 8), (2, 4, 8, 9), (3, 4, 6, 8), (4, 4, 4, 6), (3, 3, 5, 9), (1, 1, 5, 5), (3, 4, 7, 9), (1, 2, 3, 3), (1, 3, 3, 7), (1, 7, 8, 8), (1, 4, 4, 5), (4, 4, 5, 6), (2, 2, 4, 8), (3, 6, 8, 8), (1, 2, 7, 9), (1, 7, 9, 9), (1, 4, 5, 6), (2, 3, 3, 8), (4, 6, 6, 8), (3, 6, 9, 9), (1, 1, 4, 8), (5, 7, 8, 9), (1, 3, 7, 9), (5, 5, 7, 7), (2, 5, 7, 7), (1, 6, 8, 9), (4, 6, 9, 9), (4, 5, 5, 8), (1, 2, 3, 7), (5, 6, 6, 9), (3, 5, 9, 9), (4, 5, 6, 9), (1, 4, 4, 9), (1, 8, 8, 8), (2, 3, 3, 3), (2, 4, 7, 7), (2, 4, 8, 8), (2, 8, 8, 9), (5, 8, 8, 9), (4, 4, 4, 5), (2, 3, 7, 9), (1, 2, 6, 8), (3, 5, 5, 7), (1, 3, 3, 6), (6, 8, 9, 9), (1, 4, 4, 4), (2, 7, 8, 9), (2, 4, 4, 6), (1, 3, 6, 7), (2, 3, 3, 7), (1, 5, 6, 9), (1, 2, 2, 6), (5, 7, 8, 8), (3, 3, 4, 8), (1, 3, 7, 8), (4, 4, 4, 9), (2, 3, 6, 8), (1, 6, 8, 8), (2, 3, 6, 6), (4, 5, 5, 7), (1, 2, 3, 6), (6, 6, 6, 9), (2, 2, 3, 7), (1, 4, 4, 8), (5, 6, 8, 8), (4, 5, 8, 8), (5, 6, 9, 9), (6, 8, 8, 8), (3, 8, 8, 8), (1, 4, 7, 9), (1, 1, 3, 6), (1, 2, 6, 7), (3, 8, 9, 9), (3, 5, 5, 6), (3, 3, 8, 9), (2, 6, 6, 9), (7, 8, 8, 9), (6, 7, 8, 9), (2, 7, 8, 8), (2, 4, 4, 5), (1, 1, 2, 9), (1, 3, 6, 6), (2, 2, 7, 8), (1, 5, 6, 8), (1, 2, 2, 5), (3, 3, 4, 7), (3, 4, 5, 5), (4, 5, 7, 7), (2, 2, 2, 5), (2, 3, 6, 7), (1, 2, 5, 6), (2, 5, 6, 9), (4, 4, 6, 8), (6, 6, 6, 8), (2, 2, 3, 6), (1, 4, 6, 8), (4, 4, 7, 9), (2, 2, 6, 7), (1, 2, 2, 9), (2, 4, 6, 9), (3, 4, 4, 8), (4, 7, 9, 9), (1, 4, 7, 8), (1, 1, 3, 5), (4, 8, 8, 9), (3, 4, 5, 9), (2, 2, 2, 9), (3, 6, 6, 9), (2, 6, 6, 8), (1, 1, 6, 6), (2, 6, 9, 9), (2, 3, 5, 6), (3, 3, 3, 5), (2, 5, 5, 8), (3, 6, 7, 9), (1, 1, 2, 8), (1, 5, 6, 7), (1, 3, 5, 9), (2, 4, 9, 9), (3, 3, 4, 6), (4, 7, 8, 8), (3, 4, 8, 9), (5, 5, 6, 8)}\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n return tuple(sorted(nums)) in cases\n```\n### Generate True cases\nTo generate the precalculate case, we will need a correct solution first.\nThen use combinations_with_replacement in itertools to generate all possible input\n```python\nfrom itertools import combinations_with_replacement\ncases = set()\nfor case in combinations_with_replacement(range(10), 4):\n if judgePoint24(case):\n cases.append(case)\n```\n\n====================================================================================================\n\n## 2. Precalculate - False cases\nTo get more improvement, we can decrease what we place in set.\nBy just list negative case!\nThere are totally 91 cases\n``` python\n# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282590781/\n# (Time, Space) Complexity : O(1), O(1)\nbad_cases = {(4, 4, 6, 7), (2, 2, 9, 9), (1, 1, 7, 9), (1, 1, 1, 5), (1, 1, 9, 9), (2, 2, 2, 6), (1, 1, 2, 3), (5, 5, 7, 9), (3, 5, 5, 5), (1, 7, 7, 7), (1, 8, 9, 9), (2, 5, 9, 9), (3, 4, 6, 7), (2, 5, 5, 5), (1, 1, 2, 5), (1, 6, 6, 7), (1, 5, 5, 8), (5, 9, 9, 9), (6, 7, 7, 8), (1, 1, 6, 7), (1, 1, 5, 9), (2, 2, 7, 9), (6, 6, 6, 7), (1, 6, 7, 7), (7, 7, 7, 8), (1, 1, 7, 8), (5, 5, 5, 8), (7, 7, 8, 9), (1, 1, 1, 7), (6, 6, 7, 7), (3, 3, 5, 8), (1, 1, 1, 9), (4, 4, 9, 9), (1, 3, 5, 5), (1, 4, 9, 9), (2, 6, 7, 7), (1, 5, 5, 7), (2, 3, 3, 4), (1, 2, 2, 3), (5, 7, 7, 7), (1, 1, 1, 2), (2, 7, 7, 7), (6, 6, 9, 9), (1, 5, 7, 7), (5, 8, 9, 9), (8, 8, 8, 8), (3, 4, 8, 8), (2, 9, 9, 9), (6, 7, 7, 7), (4, 4, 6, 6), (5, 7, 9, 9), (8, 8, 9, 9), (1, 1, 1, 4), (2, 7, 7, 9), (8, 9, 9, 9), (7, 7, 7, 7), (1, 1, 8, 9), (1, 1, 2, 2), (2, 7, 9, 9), (5, 5, 6, 9), (4, 4, 5, 9), (7, 7, 8, 8), (7, 9, 9, 9), (4, 9, 9, 9), (1, 1, 1, 6), (1, 1, 3, 3), (1, 6, 7, 8), (7, 7, 7, 9), (4, 7, 7, 9), (1, 1, 2, 4), (1, 7, 7, 8), (7, 7, 9, 9), (9, 9, 9, 9), (6, 6, 7, 8), (2, 5, 5, 6), (1, 2, 2, 2), (7, 8, 8, 8), (1, 9, 9, 9), (1, 1, 1, 1), (6, 7, 8, 8), (2, 2, 2, 2), (3, 5, 7, 7), (7, 8, 9, 9), (6, 7, 7, 9), (1, 1, 7, 7), (5, 7, 7, 8), (1, 1, 1, 3), (5, 5, 5, 7), (1, 2, 9, 9), (6, 9, 9, 9), (8, 8, 8, 9)}\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n return tuple(sorted(nums)) not in bad_cases\n```\n### Generate False cases\nYou can generate cases by this\n```python\nfrom itertools import combinations_with_replacement\nbad_cases = set()\nfor case in combinations_with_replacement(range(1,10), 4):\n if not judgePoint24(case):\n bad_cases.add(case)\n```\n\n====================================================================================================\n\n## 3. Precalculate - False cases (let\'s go further)\nOk, since input number are restricted in 1 to 9, we can append it as a 4 digits number.\nRemember to sort the nums!!\n``` python\n# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282596555/\n# (Time, Space) Complexity : O(1), O(1)\nbad_cases = {6667, 1557, 1558, 6677, 6678, 2599, 1577, 6699, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1119, 7777, 1122, 1123, 1124, 1125, 7778, 7779, 7788, 1133, 7789, 2677, 7799, 6777, 6778, 6779, 1667, 6788, 1159, 1677, 1678, 1167, 5777, 5778, 1177, 1178, 1179, 1189, 5799, 4779, 2222, 1199, 2226, 8888, 8889, 8899, 1222, 1223, 7888, 2777, 2779, 7899, 2279, 2799, 1777, 1778, 2299, 5899, 9999, 1299, 2334, 3358, 8999, 7999, 1355, 6999, 1899, 4459, 5999, 4466, 4467, 4999, 3467, 4499, 3488, 5557, 5558, 2999, 5569, 5579, 1999, 1499, 3555, 3577, 2555, 2556}\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n return int("".join(map(str, sorted(nums)))) not in bad_cases\n```\n### Generate False cases (let\'s go further)\nSince we use combinations_with_replacement, we do not need to worry about the sorting problem.\n```python\nfrom itertools import combinations_with_replacement\nbad_cases = set()\nfor case in combinations_with_replacement(range(1,10), 4):\n if not judgePoint24(case):\n bad_cases.add(int("".join(map(str, case))))\n```\n\n====================================================================================================\n\n## 4. Precalculate - False cases (The crazy one, ver Garbled English)\nAnd finally, let\'s make a trade-off between clean code and efficiency.\nBy change number to characer can even minimize code layout space.\nUse string to store each character rather than use set will decrease effeciency but keep code cleaner.\n\n``` python\n# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282599601/\n# (Time, Space) Complexity : O(1), O(1)\nbad_cases = "\u0D1E\u04A5\u09FC\u0459\u06F2\u04C7\u1E77\u08E7\u048F\u1E6C\u0464\u0DE3\u05DB\u1A15\u0458\u22B8\u06F1\u1173\u0683\u0A75\u1193\u22B9\u1E63\u045F\u08B2\u0AD9\u1A79\u1E62\u046D\u2327\u1A7B\u045D\u270F\u176F\u049A\u068D\u1691\u0AEF\u15B6\u15B5\u15C1\u1F3F\u076B\u1B57\u1A16\u116B\u0615\u04C6\u0BB7\u1E61\u1EDB\u1387\u08AE\u15CB\u0499\u0DF9\u1A84\u045A\u0465\u0D8B\u1A0B\u0DA0\u09FB\u1692\u22C3\u04AF\u1ED0\u054B\u0462\u045C\u0513\u07CF\u16A7\u0457\u0487\u0463\u091E\u0A27\u0629\u045B\u1A7A\u08FB\u0616\u12AB\u049B\u170B\u1172\u0ADB\u1E6D\u068E\u1A2B"\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n return chr(int(\'\'.join(map(str, sorted(nums)))) + 0) not in bad_cases\n```\n### Generate False cases (The crazy one, ver Garbled English)\n```python\nfrom itertools import combinations_with_replacement\ncases = set()\nfor case in combinations_with_replacement(range(1,10), 4):\n if not judgePoint24(case):\n cases.add(chr(int("".join(map(str, case)))))\ns = "".join(cases)\n```\n\n====================================================================================================\n\n## 5. Precalculate - False cases (The crazy one, ver Garbled Chinese)\nIf you afraid the symbol that can\'t show on screen, try Chinese version\nBy shift symbol to unicode Chinese range where start from 19968, you store it in Chinese\n``` python\n# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282598893/\n# (Time, Space) Complexity : O(1), O(1)\nbad_cases = "\u687B\u5B8B\u525A\u63C1\u5299\u70B8\u5258\u548D\u5415\u6816\u63B5\u6187\u5313\u529A\u6C77\u58D9\u58DB\u5262\u70B9\u58EF\u56E7\u53DB\u5F73\u525D\u6C62\u63B6\u5BF9\u526D\u5263\u5264\u6C6C\u5F93\u56FB\u55CF\u6C6D\u6492\u5827\u52C6\u57FB\u5265\u525F\u656F\u6491\u6884\u60AB\u6CDB\u6C63\u750F\u57FC\u5429\u525B\u5259\u6D3F\u54F1\u5287\u6815\u63CB\u548E\u7127\u5BA0\u6879\u52AF\u6C61\u525C\u534B\u556B\u680B\u5875\u52A5\u5483\u5BE3\u650B\u6957\u52C7\u56AE\u5B1E\u6CD0\u70C3\u571E\u528F\u5416\u56B2\u682B\u5F72\u687A\u5257\u64A7\u54F2\u59B7\u5F6B\u529B"\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n return chr(int(\'\'.join(map(str, sorted(nums)))) + 19968) not in bad_cases\n```\n### Generate False cases (The crazy one, ver Garbled Chinese)\n```python\nfrom itertools import combinations_with_replacement\ncases = set()\nfor case in combinations_with_replacement(range(1,10), 4):\n if not judgePoint24(case):\n cases.add(chr(int("".join(map(str, case)))+19968))\ns = "".join(cases)\n```
4
3
['Python', 'Python3']
0
24-game
Python, Functional style
python-functional-style-by-awice-qnu1
We write a function apply that takes two sets of possibilities for A and B and returns all possible results operator(A, B) or operator(B, A) for all possible op
awice
NORMAL
2017-09-17T05:35:10.366000+00:00
2017-09-17T05:35:10.366000+00:00
1,344
false
We write a function `apply` that takes two sets of possibilities for A and B and returns all possible results `operator(A, B)` or `operator(B, A)` for all possible operators.\n\nIgnoring reflection, there are only two ways we can apply the operators: (AB)(CD) or ((AB)C)D. When C and D are ordered, this becomes three ways - the third way is ((AB)D)C.\n\nThis solution is a little slow because it has to manage sets - my article has a solution that is almost 10x faster. I think this one is cool though.\n\n```\ndef judgePoint24(self, nums):\n from operator import truediv, mul, add, sub\n from fractions import Fraction\n\n def apply(A, B):\n ans = set()\n for x, y, op in itertools.product(A, B, (truediv, mul, add, sub)):\n if op is not truediv or y: ans.add(op(x, y))\n if op is not truediv or x: ans.add(op(y, x))\n return ans\n \n A = [{x} for x in map(Fraction, nums)]\n for i, j in itertools.combinations(range(4), 2):\n r1 = apply(A[i], A[j])\n k, l = {0, 1, 2, 3} - {i, j}\n if 24 in apply(apply(r1, A[k]), A[l]): return True\n if 24 in apply(apply(r1, A[l]), A[k]): return True\n if 24 in apply(r1, apply(A[k], A[l])): return True\n \n return False\n```
4
1
[]
2
24-game
24 Game DFS
24-game-dfs-by-tanmaybhujade-todc
\n\n# Code\n\nclass Solution {\n private final char[] ops = {\'+\', \'-\', \'*\', \'/\'};\n\n public boolean judgePoint24(int[] cards) {\n List<Dou
tanmaybhujade
NORMAL
2024-03-29T17:15:08.897839+00:00
2024-03-29T17:15:08.897861+00:00
815
false
\n\n# Code\n```\nclass Solution {\n private final char[] ops = {\'+\', \'-\', \'*\', \'/\'};\n\n public boolean judgePoint24(int[] cards) {\n List<Double> nums = new ArrayList<>();\n for (int num : cards) {\n nums.add((double) num);\n }\n return dfs(nums);\n }\n\n private boolean dfs(List<Double> nums) {\n int n = nums.size();\n if (n == 1) {\n return Math.abs(nums.get(0) - 24) < 1e-6;\n }\n boolean ok = false;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n if (i != j) {\n List<Double> nxt = new ArrayList<>();\n for (int k = 0; k < n; ++k) {\n if (k != i && k != j) {\n nxt.add(nums.get(k));\n }\n }\n for (char op : ops) {\n switch (op) {\n case \'/\' -> {\n if (nums.get(j) == 0) {\n continue;\n }\n nxt.add(nums.get(i) / nums.get(j));\n }\n case \'*\' -> {\n nxt.add(nums.get(i) * nums.get(j));\n }\n case \'+\' -> {\n nxt.add(nums.get(i) + nums.get(j));\n }\n case \'-\' -> {\n nxt.add(nums.get(i) - nums.get(j));\n }\n }\n ok |= dfs(nxt);\n if (ok) {\n return true;\n }\n nxt.remove(nxt.size() - 1);\n }\n }\n }\n }\n return ok;\n }\n}\n```
3
0
['Java']
0
24-game
[C++] Simple C++ Code
c-simple-c-code-by-prosenjitkundu760-afmz
\n# If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.\n\nclass Solution {\n d
_pros_
NORMAL
2022-08-19T06:41:49.107854+00:00
2022-08-19T06:42:35.954633+00:00
493
false
\n# **If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.**\n```\nclass Solution {\n double error=0.001;\n vector<double> opnxy(double x, double y)\n {\n vector<double> ans;\n if(x > error)\n ans.push_back(x/y);\n if(y > error)\n ans.push_back(y/x);\n ans.push_back(x+y);\n ans.push_back(x*y);\n ans.push_back(x-y);\n ans.push_back(y-x);\n return ans;\n }\n bool dfs(vector<double> &dbl)\n {\n if(dbl.size() == 1){\n if(abs(24-dbl[0]) < error)\n return true;\n return false;\n }\n for(int i = 0; i < dbl.size(); i++)\n {\n for(int j = 0; j < i; j++)\n {\n if(i == j)\n continue;\n double x = dbl[i], y = dbl[j];\n vector<double> opn = opnxy(x, y);\n dbl.erase(dbl.begin()+i);\n dbl.erase(dbl.begin()+j);\n for(double &val : opn)\n {\n dbl.push_back(val);\n if(dfs(dbl)) return true;\n dbl.pop_back();\n }\n dbl.insert(dbl.begin()+j,y);\n dbl.insert(dbl.begin()+i,x);\n }\n }\n return false;\n }\npublic:\n bool judgePoint24(vector<int>& cards) {\n vector<double> dbl (cards.begin(),cards.end());\n return dfs(dbl);\n }\n};\n```
3
0
['Backtracking', 'C']
0
24-game
Easy C++ Solution
easy-c-solution-by-shreya1393-xq64
\nclass Solution {\npublic:\n bool helper(vector<float> cards) {\n int n = cards.size();\n // cout << "size is " << n << endl;\n if (n ==
shreya1393
NORMAL
2021-12-31T20:36:47.579712+00:00
2021-12-31T20:36:47.579742+00:00
568
false
```\nclass Solution {\npublic:\n bool helper(vector<float> cards) {\n int n = cards.size();\n // cout << "size is " << n << endl;\n if (n == 1) {\n //cout << cards[0] << endl;\n if (abs(cards[0]-24) < 0.001) {\n return true;\n }\n return false;\n }\n \n if (n < 1) {\n return false;\n }\n \n for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n vector<float> poss;\n poss.push_back(cards[i]+cards[j]);\n poss.push_back(abs(cards[i]-cards[j]));\n poss.push_back(cards[i]*cards[j]);\n \n if (cards[j] > 0) {\n poss.push_back(cards[i]/cards[j]);\n }\n \n if (cards[i] > 0) {\n poss.push_back(cards[j]/cards[i]);\n }\n \n vector<float> temp;\n for (int k = 0; k < n; k++) {\n if (k == i || k == j) {\n continue;\n }\n temp.push_back(cards[k]);\n }\n \n for (auto l : poss) {\n temp.push_back(l);\n if (helper(temp)) {\n return true;\n }\n temp.pop_back();\n }\n }\n }\n return false;\n }\n \n bool judgePoint24(vector<int>& cards) {\n vector<float> temp;\n for (auto i : cards) {\n temp.push_back(i);\n }\n return helper(temp);\n }\n};\n```
3
0
['Backtracking']
3
24-game
Python beats 99% - hopefully clear code and explanation
python-beats-99-hopefully-clear-code-and-k3ql
\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n \n self.allcombos = []\n \n # need all combinations of ca
thess24
NORMAL
2021-12-27T04:59:47.933096+00:00
2021-12-27T05:09:40.209004+00:00
802
false
```\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n \n self.allcombos = []\n \n # need all combinations of cards\n def permute(arr,remcards):\n if len(arr)==4:\n self.allcombos.append(arr[:])\n return\n \n for i,card in enumerate(remcards):\n arr.append(card)\n combos(arr,remcards[:i]+remcards[i+1:])\n arr.pop() \n \n # then all combinations of operations for all parens placements\n def calculate(cards):\n if len(cards)<=1:\n return cards\n else:\n values = set()\n\t\t\t\tleft = calculate(cards[:splitidx])\n\t\t\t\tright = calculate(cards[splitidx:])\n for splitidx in range(1,len(cards)):\n for lval in left:\n for rval in right:\n values.add(lval+rval)\n values.add(lval-rval)\n values.add(lval*rval)\n if rval!=0:\n values.add(lval/rval)\n return values\n \n permute([],cards)\n for combo in self.allcombos:\n for c in calculate(combo):\n if c>23.99 and c<24.01: return True\n return False\n```\n\nThe permute function just comes up will all permuations of the cards list. There are other leetcode quesitons that handle this portion or you can use itertools.permutations as well (I implemented a backtracking solution for practice).\n\nThe tricker part of this is coming up with how to have every combination of parens and every combination of operator. I implemented this recursively. The trick is to have a function that calculates all possible values for the cards on the left and cards on the right of a \'split\'. \n\nAs an example, you might have the cards [4,1,2,5]. You can split this into ([4] and [1,2,5]) or ([4,1] and [2,5]) or ([4] and [1,2,5]). What we want is to calculate all possible values for each of these splits and then apply our operators to both sides. When we have the split on idx 2 ([4,1] and [2,5]) we come up with left values like 4+1 = 5, 4-1 = 3, 4*1=4, 4/1=4 and do the same for the right side. What gets returned is [5,3,4] (removing duplicates) for the left side and some other list of values for the right side. Then we apply all of our operators to each pairing in both lists.\n\nBesides that we just go through the outputs for each permutation of cards and see if 24 shows up.\n\nThats it!\n\nThe above code beats 95% -- if you use itertools.permutations it beats 99%\n\n``` \ndef calculate(cards):\n\tif len(cards)<=1:\n\t\treturn cards\n\telse:\n\t\tvalues = set()\n\t\tfor splitidx in range(1,len(cards)):\n\t\t\tfor lval in calculate(cards[:splitidx]):\n\t\t\t\tfor rval in calculate(cards[splitidx:]):\n\t\t\t\t\tvalues.add(lval+rval)\n\t\t\t\t\tvalues.add(lval-rval)\n\t\t\t\t\tvalues.add(lval*rval)\n\t\t\t\t\tif rval!=0:\n\t\t\t\t\t\tvalues.add(lval/rval)\n\t\treturn values\n\nfor combo in itertools.permutations(cards):\n\tfor c in calculate(combo):\n\t\tif c>23.99 and c<24.01: return True\nreturn False\n\t\t```
3
0
['Python']
1
24-game
Python | Backtracking | Also generates the solution expressions
python-backtracking-also-generates-the-s-49df
I was asked this question in a technical interview, with a slight variation--instead of a boolean, they wanted me to return a list of the expressions that would
GracelessGhost
NORMAL
2021-10-22T06:34:58.223809+00:00
2021-10-22T06:36:15.450535+00:00
735
false
I was asked this question in a technical interview, with a slight variation--instead of a boolean, they wanted me to return a list of the expressions that would reach the target number. This was my solution. The basic idea is:\n\n1. Since every operation is binary, you can partition the list of nums into two entities.\n2. Perform every possible arithmetic operation between those two entities.\n3. If an entity has multiple numbers in it, recurse within that entity.\n4. Repeat steps 1-3 with every possible binary partition of the list.\n\n```\nclass Solution:\n def powerset(self, iterable):\n """ powerset([1, 2, 3]) -> [1] [2] [3] [1, 2] [1, 3] [2, 3] """\n s = list(iterable)\n sets = chain.from_iterable(combinations(s, r) for r in range(1, len(s)))\n return [list(tup) for tup in sets]\n\n def getComplement(self, cards, subset):\n c1 = Counter(cards)\n c2 = Counter(subset)\n return list((c1 - c2).elements())\n\n def getOperations(self, left, right):\n ans = []\n for n1 in left:\n for n2 in right:\n ans.append(f\'({n1} + {n2})\')\n ans.append(f\'({n1} - {n2})\')\n ans.append(f\'({n1} * {n2})\')\n ans.append(f\'({n2} - {n1})\')\n if n2 != \'0\':\n ans.append(f\'({n1} / {n2})\')\n if n1 != \'0\':\n ans.append(f\'({n2} / {n1})\')\n return ans\n\n def getPossibleAnswers(self, cards):\n if len(cards) == 1:\n return cards\n else:\n subsets = list(self.powerset(cards))\n subsets = subsets[:len(subsets) // 2] # Avoid duplicates\n ans = []\n for subset in subsets:\n left = self.getPossibleAnswers(subset)\n right = self.getPossibleAnswers(self.getComplement(cards, subset))\n ans += self.getOperations(left, right)\n return ans\n\n def judgePoint24(self, cards: list[int]) -> list[str]:\n possible = self.getPossibleAnswers(cards)\n ans = []\n for expression in possible:\n try:\n if round(eval(expression), 3) == 24:\n ans.append(expression)\n except ZeroDivisionError:\n pass\n return ans\n```
3
0
['Backtracking', 'Python']
1
24-game
Simple, clean python (beats 98%)
simple-clean-python-beats-98-by-bingoban-sg8o
\timport itertools\n\tclass Solution:\n\t\tdef judgePoint24(self, cards: List[int]) -> bool:\n\n\t\t\t@lru_cache(None)\n\t\t\tdef helper(nums):\n\t\t\t\tif(len(
bingobango3846
NORMAL
2021-08-16T21:43:11.130372+00:00
2021-08-16T21:43:11.130406+00:00
438
false
\timport itertools\n\tclass Solution:\n\t\tdef judgePoint24(self, cards: List[int]) -> bool:\n\n\t\t\t@lru_cache(None)\n\t\t\tdef helper(nums):\n\t\t\t\tif(len(nums) == 1):\n\t\t\t\t\treturn nums\n\t\t\t\t\t\n\t\t\t\tpossible = set()\n\t\t\t\tfor i in range(1, len(nums)):\n\t\t\t\t\tleft = helper(nums[0:i])\n\t\t\t\t\tright = helper(nums[i:])\n\t\t\t\t\tfor l in left:\n\t\t\t\t\t\tfor r in right:\n\t\t\t\t\t\t\tpossible.update([l+r, l-r, l*r, r and l/r])\n\t\t\t\treturn possible\n\n\t\t\tfor perm in itertools.permutations(cards):\n\t\t\t\tans = helper(perm)\n\t\t\t\tif(any([abs(24-n)<=0.001 for n in ans])):\n\t\t\t\t\treturn True\n\n\t\t\treturn False\n
3
1
[]
1
24-game
C++
c-by-wangjiacode-iytm
C++\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n vector<double> a(nums.begin(), nums.end());\n return dfs(a);\n }\n
wangjiacode
NORMAL
2021-03-11T07:41:35.505543+00:00
2021-03-11T07:41:35.505575+00:00
315
false
```C++\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n vector<double> a(nums.begin(), nums.end());\n return dfs(a);\n }\n vector<double> get(int i, int j, double c, vector<double>& nums) {\n vector<double> res;\n for (int k = 0; k < nums.size(); k ++) {\n if (k != i && k != j) {\n res.push_back(nums[k]);\n }\n }\n res.push_back(c);\n return res;\n }\n bool dfs(vector<double> nums) {\n if (nums.size() == 1) return fabs(nums[0] - 24) <= 1e-8;\n for (int i = 0; i < nums.size(); i ++)\n for (int j = 0; j < nums.size(); j ++) {\n if (i != j) {\n double a = nums[i], b = nums[j];\n if (dfs(get(i, j, a + b, nums))) return true;\n if (dfs(get(i, j, a - b, nums))) return true;\n if (dfs(get(i, j, a * b, nums))) return true;\n if (b && dfs(get(i, j, a / b, nums))) return true;\n }\n }\n return false;\n }\n};\n```
3
0
[]
1
24-game
[JAVA] Simple DFS solution
java-simple-dfs-solution-by-final_destin-vr5l
``` \npublic boolean judgePoint24(int[] nums) {\n ArrayList list = new ArrayList<>();\n for(int i: nums){\n list.add((double)i);\n
final_destiny
NORMAL
2020-12-28T03:38:27.552550+00:00
2020-12-28T03:38:27.552582+00:00
326
false
``` \npublic boolean judgePoint24(int[] nums) {\n ArrayList<Double> list = new ArrayList<>();\n for(int i: nums){\n list.add((double)i);\n }\n \n return dfs(list);\n \n }\n \n boolean dfs(List<Double> list) {\n if (list.size() == 0) return false;\n \n if(list.size() == 1){\n if(Math.abs(list.get(0) - 24) < 0.001){\n return true;\n } else {\n return false;\n }\n }\n \n for(int i=0; i<list.size(); i++){\n for(int j=i+1; j<list.size(); j++){\n \n double num1 = list.get(i);\n double num2 = list.get(j);\n\n List<Double> possibleResult = new ArrayList<>();\n\n possibleResult.add(num1-num2);\n possibleResult.add(num2-num1);\n possibleResult.add(num1+num2);\n possibleResult.add(num1*num2);\n if(num2!=0) possibleResult.add(num1/num2);\n if(num1!=0) possibleResult.add(num2/num1);\n\n for(int k=0; k< possibleResult.size(); k++){\n List<Double> temp = new ArrayList<>();\n temp.add(possibleResult.get(k));\n\n for(int l=0; l<list.size(); l++) {\n if(l!=i && l!=j) {\n temp.add(list.get(l));\n }\n }\n\n if(dfs(temp)) {\n return true;\n }\n } \n }\n }\n \n return false;\n }
3
0
[]
0
24-game
C++ clean and fast
c-clean-and-fast-by-yytlc-igjp
\nclass Solution {\nvector<double> v;\nbool flag = false;\n\nvoid dfs(int n){\n \n if(n == 1){\n if(abs(v[0] - 24) <= 0.0000001){\n flag
yytlc
NORMAL
2020-05-07T08:23:15.562646+00:00
2020-05-07T08:23:15.562683+00:00
268
false
```\nclass Solution {\nvector<double> v;\nbool flag = false;\n\nvoid dfs(int n){\n \n if(n == 1){\n if(abs(v[0] - 24) <= 0.0000001){\n flag = true;\n }\n return;\n }\n \n for(int i = 0; i < n; ++i){\n for(int j = i + 1; j < n; ++j){\n double a = v[i];\n double b = v[j];\n \n v[i] = a + b;\n v[j] = v[n-1];\n dfs(n-1);\n \n v[i] = a - b;\n v[j] = v[n-1];\n dfs(n-1);\n \n v[i] = b - a;\n v[j] = v[n-1];\n dfs(n-1); \n\n v[i] = a * b;\n v[j] = v[n-1];\n dfs(n-1); \n\n if(b != 0){\n v[i] = a / b;\n v[j] = v[n-1];\n dfs(n-1);\n }\n\n if(a != 0){\n v[i] = b / a;\n v[j] = v[n-1];\n dfs(n-1);\n }\n \n v[i] = a;\n v[j] = b;\n }\n }\n} \n \npublic:\n bool judgePoint24(vector<int>& nums) {\n v.resize(4, 0.0);\n v[0] = (double) nums[0];\n v[1] = (double) nums[1];\n v[2] = (double) nums[2];\n v[3] = (double) nums[3];\n \n dfs(4);\n return flag;\n }\n};\n```
3
0
[]
0
24-game
Clean C++ solution using Rational class
clean-c-solution-using-rational-class-by-6tpy
c++\nclass Rational {\npublic:\n Rational() {}\n Rational(int num) : Rational(num, 1) {}\n \n bool is(int target) const {\n if (denom == 0 ||
kibeom
NORMAL
2018-12-04T00:54:06.822993+00:00
2018-12-04T00:54:06.823049+00:00
334
false
```c++\nclass Rational {\npublic:\n Rational() {}\n Rational(int num) : Rational(num, 1) {}\n \n bool is(int target) const {\n if (denom == 0 || num % denom != 0)\n return false;\n return num / denom == target;\n }\n\n friend Rational operator+(const Rational &lhs, const Rational &rhs) {\n return Rational{lhs.num * rhs.denom + lhs.denom * rhs.num, lhs.denom * rhs.denom};\n }\n friend Rational operator-(const Rational &lhs, const Rational &rhs) {\n return Rational{lhs.num * rhs.denom - lhs.denom * rhs.num, lhs.denom * rhs.denom};\n }\n friend Rational operator*(const Rational &lhs, const Rational &rhs) {\n return Rational{lhs.num * rhs.num, lhs.denom * rhs.denom};\n }\n friend Rational operator/(const Rational &lhs, const Rational &rhs) {\n return Rational{lhs.num * rhs.denom, lhs.denom * rhs.num};\n }\n\nprivate:\n Rational(int num, int denom) : num(num), denom(denom) {}\n\n int num;\n int denom;\n};\n\n\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n return judgePoint24<4>({nums[0], nums[1], nums[2], nums[3]});\n }\n\n bool judgePoint24(const array<Rational, 1>& nums) {\n return nums[0].is(24);\n }\n\n template <size_t N>\n bool judgePoint24(const array<Rational, N>& nums) {\n for(int i = 0; i < nums.size(); ++i) {\n for(int j = i + 1; j < nums.size(); ++j) {\n if (judgePoint24(compute(nums, i, j, plus<Rational>())) ||\n judgePoint24(compute(nums, i, j, minus<Rational>())) ||\n judgePoint24(compute(nums, j, i, minus<Rational>())) ||\n judgePoint24(compute(nums, i, j, multiplies<Rational>())) ||\n judgePoint24(compute(nums, i, j, divides<Rational>())) ||\n judgePoint24(compute(nums, j, i, divides<Rational>())))\n return true;\n }\n }\n return false;\n }\n\n template <typename T, size_t N>\n array<Rational, N-1> compute(const array<Rational, N> &nums, int i, int j, T op) {\n array<Rational, N-1> result;\n result[0] = op(nums[i], nums[j]);\n\n int index = 1;\n for (int k = 0; k < N; ++k)\n if (k != i && k != j)\n result[index++] = nums[k];\n\n return result;\n }\n};\n```
3
0
[]
1
24-game
AC C++ solution beats 100%, easy to understand
ac-c-solution-beats-100-easy-to-understa-d2fq
AC C++ solution beats 100%, easy to understand\n\n bool game(vector<double> & nums,int n)\n {\n if(n==1)\n {\n if(fabs(nums[0]-24)<1
zyy344858
NORMAL
2018-08-15T01:25:50.236370+00:00
2018-10-25T16:03:28.547124+00:00
512
false
AC C++ solution beats 100%, easy to understand\n```\n bool game(vector<double> & nums,int n)\n {\n if(n==1)\n {\n if(fabs(nums[0]-24)<1e-6)\n return true;\n else \n return false;\n \n \n \n }\n \n for(int i=0;i<n;i++)\n {for(int j=i+1;j<n;j++)\n {\n double a=nums[i];\n double b=nums[j];\n nums[j]=nums[n-1];\n \n nums[i]=a+b;\n if(game(nums,n-1))\n return true;\n \n \n nums[i]=a-b;\n if(game(nums,n-1))\n return true;\n \n \n nums[i]=b-a;\n if(game(nums,n-1))\n return true; \n \n \n nums[i]=b*a;\n if(game(nums,n-1))\n return true; \n \n if(b!=0)\n {\n nums[i]=a/b;\n if(game(nums,n-1))\n return true; \n }\n \n if(a!=0)\n {\n nums[i]=b/a;\n if(game(nums,n-1))\n return true; \n \n }\n nums[i]=a;\n nums[j]=b;\n \n \n }}\n return false;\n \n \n \n \n \n }\n \n bool judgePoint24(vector<int>& nums) {\n vector<double> qq(nums.size(),0.0);\n for(int i=0;i<4;i++)\n qq[i]=(double)nums[i];\n return game(qq,4);\n \n }\n```
3
0
[]
0
24-game
Very Short and Clean Solution
very-short-and-clean-solution-by-charnav-4nbb
null
charnavoki
NORMAL
2025-02-27T13:07:30.751697+00:00
2025-02-27T13:07:30.751697+00:00
146
false
```javascript [] const ops = [(a, b) => a + b, (a, b) => a - b, (a, b) => b - a, (a, b) => a * b, (a, b) => a / b, (a, b) => b / a]; const judgePoint24 = (nums, [a, b, c, d] = nums) => { switch (nums.length) { case 4: return [[a, b, c, d], [a, c, b, d], [a, d, c, b], [b, c, a, d], [b, d, a, c], [c, d, a, b]] .some(([w, x, y, z]) => ops.some(f => judgePoint24([f(w, x), y, z]))); case 3: return [[a, b, c], [b, c, a], [a, c, b]].some(([x, y, z]) => ops.some(f => judgePoint24([f(x, y), z]))); case 2: return ops.some(f => judgePoint24([f(a, b)])); default: return a > 23.999420 && a < 24.0001488; } }; ```
2
0
['JavaScript']
0
24-game
Rust || 1ms || beats 100%
rust-1ms-beats-100-by-user7454af-wt36
Complexity\n- Time complexity: O(2^n) = O(2^4)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(2^n) = O(2^4)\n Add your space complexity he
user7454af
NORMAL
2024-06-14T22:47:08.396518+00:00
2024-06-14T22:47:08.396554+00:00
129
false
# Complexity\n- Time complexity: $$O(2^n) = O(2^4)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(2^n) = O(2^4)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimpl Solution {\n pub fn judge_point24(mut cards: Vec<i32>) -> bool {\n let cards = cards.into_iter().map(|c| c as f64).collect::<Vec<_>>();\n fn prod_div_sum_diff(a: f64, b: f64) -> [f64; 6] {\n [a * b, if b == 0.0 {f64::MAX} else {a/b}, if a == 0.0 {f64::MAX} else {b/a},\n a + b, a - b, b - a]\n };\n fn dfs(cards: &Vec<f64>) -> bool {\n if cards.len() == 1 {\n return (cards[0] - 24.0).abs() < 0.001;\n }\n for i in 0..cards.len() {\n for j in i+1..cards.len() {\n let mut new_cards = vec![];\n for k in 0..cards.len() {\n if k != i && k != j {\n new_cards.push(cards[k]);\n }\n }\n for &result in prod_div_sum_diff(cards[i], cards[j]).iter() {\n if result == f64::MAX {\n continue;\n }\n new_cards.push(result);\n if dfs(&new_cards) {\n return true;\n }\n new_cards.pop();\n }\n }\n }\n false\n }\n dfs(&cards)\n }\n}\n```
2
0
['Rust']
0
24-game
Solution
solution-by-deleted_user-n2qe
C++ []\nclass Solution {\npublic:\n std::vector<double> available_nums;\n bool bt() {\n if (available_nums.size() == 1) {\n auto v = ava
deleted_user
NORMAL
2023-04-18T12:42:02.262196+00:00
2023-04-18T12:53:54.683859+00:00
1,116
false
```C++ []\nclass Solution {\npublic:\n std::vector<double> available_nums;\n bool bt() {\n if (available_nums.size() == 1) {\n auto v = available_nums.back();\n return abs(v - 24.) < .01;\n }\n for (size_t i = 0; i < available_nums.size(); ++i) {\n for (size_t j = i + 1; j < available_nums.size(); j++)\n {\n auto op1 = available_nums[i];\n auto op2 = available_nums[j];\n available_nums.erase(available_nums.begin() + j);\n available_nums.erase(available_nums.begin() + i);\n auto bt_help = [&](double curr) {\n available_nums.push_back(curr);\n if (bt()) return true;\n available_nums.pop_back();\n return false;\n };\n if (bt_help(op1 + op2)) return true;\n if (bt_help(op1 - op2)) return true;\n if (bt_help(op2 - op1)) return true;\n if (bt_help(op1 / op2)) return true;\n if (bt_help(op2 / op1)) return true;\n if (bt_help(op2 * op1)) return true;\n available_nums.insert(available_nums.begin() + i, op1);\n available_nums.insert(available_nums.begin() + j, op2);\n }\n }\n return false;\n }\n bool judgePoint24(vector<int>& cards) {\n for (const auto card : cards) {\n available_nums.push_back(card);\n }\n return bt();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n if len(cards) == 2:\n return abs((cards[0] + cards[1]) - 24) < 0.00001 or \\\n abs((cards[0] * cards[1]) - 24) < 0.00001 or \\\n abs((cards[0] - cards[1]) - 24) < 0.00001 or \\\n abs((cards[1] - cards[0]) - 24) < 0.00001 or \\\n abs((cards[1] and (cards[0] / cards[1])) - 24) < 0.00001 or \\\n abs((cards[0] and (cards[1] / cards[0])) - 24) < 0.00001\n\n for i in range(len(cards) - 1):\n cards[0], cards[i] = cards[i], cards[0]\n for j in range(i+1, len(cards)):\n cards[1], cards[j] = cards[j], cards[1]\n computations = [\n cards[0] + cards[1],\n cards[0] * cards[1],\n cards[0] - cards[1],\n cards[1] - cards[0],\n cards[1] and cards[0] / cards[1],\n cards[0] and cards[1] / cards[0]\n ]\n remaining = cards[2:]\n for computation in computations:\n found = self.judgePoint24(remaining + [computation])\n if found:\n return True\n cards[1], cards[j] = cards[j], cards[1]\n cards[0], cards[i] = cards[i], cards[0]\n return False\n```\n\n```Java []\nclass Solution {\n private static final double EPS = 1e-6;\n private boolean backtrack(double[] A, int n) {\n if(n == 1) return Math.abs(A[0] - 24) < EPS;\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n double a = A[i], b = A[j];\n A[j] = A[n-1];\n A[i] = a + b;\n if(backtrack(A, n - 1)) return true;\n A[i] = a - b;\n if(backtrack(A, n - 1)) return true;\n A[i] = b - a;\n if(backtrack(A, n - 1)) return true;\n A[i] = a * b;\n if(backtrack(A, n - 1)) return true;\n if(Math.abs(b) > EPS) {\n A[i] = a / b;\n if(backtrack(A, n - 1)) return true;\n }\n if(Math.abs(a) > EPS) {\n A[i] = b / a;\n if(backtrack(A, n - 1)) return true;\n }\n A[i] = a; A[j] = b;\n }\n }\n return false;\n }\n public boolean judgePoint24(int[] nums) {\n double[] A = new double[nums.length];\n for(int i = 0; i < nums.length; i++) A[i] = nums[i];\n return backtrack(A, A.length);\n }\n}\n```\n
2
0
['C++', 'Java', 'Python3']
1
24-game
Easy C++ Solution | Trial & Error Method
easy-c-solution-trial-error-method-by-ra-633k
\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& cards) {\n return solve(vector<double>(cards.begin(),cards.end()));\n }\n vector<d
rac101ran
NORMAL
2022-10-07T13:06:24.725529+00:00
2022-10-07T13:06:24.725573+00:00
955
false
```\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& cards) {\n return solve(vector<double>(cards.begin(),cards.end()));\n }\n vector<double> solveType(double x,double y) {\n return {x + y,x - y,x * y,y - x, x / y , y / x};\n }\n bool solve(vector<double> a) {\n if(a.size() == 1) return abs(a[0] - 24) < 0.0001; // if a is reduced to 1 size then just check\n for(int i=0; i<a.size(); i++) {\n for(int j=i+1; j<a.size(); j++) {\n for(double x : solveType(a[i],a[j])) { // possibilites of 2 numbers\n vector<double> other;\n other.push_back(x);\n for(int k=0; k<a.size(); k++) {\n if(k!=i && k!=j) other.push_back(a[k]); // add remaining elements\n }\n if(solve(other)) return true; // compute now for a.size() - 1 elements , reduce size of a \n }\n }\n }\n return false;\n }\n};\n```
2
0
['Math', 'C']
0
24-game
easy c
easy-c-by-balsi2oo1-sa7p
\nbool judgePoint24(int* nums, int numsSize){\n double a=nums[0],b=nums[1],c=nums[2],d=nums[3];\n return judgePoint24_4(a,b,c,d);\n}\nint judgePoint24_1(dou
balsi2OO1
NORMAL
2022-04-25T08:19:26.046357+00:00
2022-04-25T08:19:26.046406+00:00
200
false
```\nbool judgePoint24(int* nums, int numsSize){\n double a=nums[0],b=nums[1],c=nums[2],d=nums[3];\n return judgePoint24_4(a,b,c,d);\n}\nint judgePoint24_1(double a){\n return a-24>-1e-6 && a-24<1e-6;\n}\nint judgePoint24_2(double a,double b){\n return (judgePoint24_1(a+b)||\n judgePoint24_1(a*b)||\n judgePoint24_1(a-b)||\n judgePoint24_1(b-a)||\n judgePoint24_1(a/b)||\n judgePoint24_1(b/a));\n}\nint judgePoint24_3(double a,double b,double c){\n return (judgePoint24_2((b+c),a)||\n judgePoint24_2((b*c),a)||\n judgePoint24_2((b-c),a)||\n judgePoint24_2((c-b),a)||\n judgePoint24_2((b/c),a)||\n judgePoint24_2((c/b),a)||\n judgePoint24_2((a+c),b)||\n judgePoint24_2((a*c),b)||\n judgePoint24_2((a-c),b)||\n judgePoint24_2((c-a),b)||\n judgePoint24_2((a/c),b)||\n judgePoint24_2((c/a),b)||\n judgePoint24_2((a+b),c)||\n judgePoint24_2((a*b),c)||\n judgePoint24_2((a-b),c)||\n judgePoint24_2((b-a),c)||\n judgePoint24_2((a/b),c)||\n judgePoint24_2((b/a),c));\n}\nint judgePoint24_4(double a,double b,double c,double d){\n return \n (judgePoint24_3((c+d),a,b)||\n judgePoint24_3((c*d),a,b)||\n judgePoint24_3((c-d),a,b)||\n judgePoint24_3((d-c),a,b)||\n judgePoint24_3((c/d),a,b)||\n judgePoint24_3((d/c),a,b)||\n judgePoint24_3((b+d),a,c)||\n judgePoint24_3((b*d),a,c)||\n judgePoint24_3((b-d),a,c)||\n judgePoint24_3((d-b),a,c)||\n judgePoint24_3((b/d),a,c)||\n judgePoint24_3((d/b),a,c)||\n judgePoint24_3((b+c),a,d)||\n judgePoint24_3((b*c),a,d)||\n judgePoint24_3((b-c),a,d)||\n judgePoint24_3((c-b),a,d)||\n judgePoint24_3((b/c),a,d)||\n judgePoint24_3((c/b),a,d)||\n judgePoint24_3((a+d),b,c)||\n judgePoint24_3((a*d),b,c)||\n judgePoint24_3((a-d),b,c)||\n judgePoint24_3((d-a),b,c)||\n judgePoint24_3((a/d),b,c)||\n judgePoint24_3((d/a),b,c)||\n judgePoint24_3((a+c),b,d)||\n judgePoint24_3((a*c),b,d)||\n judgePoint24_3((a-c),b,d)||\n judgePoint24_3((c-a),b,d)||\n judgePoint24_3((a/c),b,d)||\n judgePoint24_3((c/a),b,d)||\n judgePoint24_3((a+b),c,d)||\n judgePoint24_3((a*b),c,d)||\n judgePoint24_3((a-b),c,d)||\n judgePoint24_3((b-a),c,d)||\n judgePoint24_3((a/b),c,d)||\n judgePoint24_3((b/a),c,d));\n}\n\n```
2
0
['C']
1
24-game
[Python3] dp
python3-dp-by-ye15-1hdq
\n\nfrom fractions import Fraction\n\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n \n @cache\n def fn(*args): \
ye15
NORMAL
2021-12-02T22:30:56.791842+00:00
2021-12-02T22:33:30.577423+00:00
388
false
\n```\nfrom fractions import Fraction\n\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n \n @cache\n def fn(*args): \n """Return True if arguments can be combined into 24."""\n if len(args) == 1: return args[0] == 24\n for x, y, *rem in permutations(args): \n for op in add, sub, mul, Fraction: \n if (op != Fraction or y != 0) and fn(op(x, y), *rem): return True\n return False \n \n return fn(*cards)\n```
2
0
['Python3']
0
24-game
Python3 - clean code
python3-clean-code-by-karrenbelt-ie7d
python\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n # I use fractions because of floating point arithmetic\n # size i
karrenbelt
NORMAL
2021-08-12T09:25:34.599957+00:00
2021-08-12T09:26:54.967584+00:00
416
false
```python\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n # I use fractions because of floating point arithmetic\n # size is 24 [nums] x 64 [operators] x 2 [precedence]\n from operator import add, sub, mul\n from fractions import Fraction\n from itertools import permutations, product\n\n def div(x, y):\n return x / y if y else 0\n\n operators = [add, sub, mul, div]\n for (a, b, c, d) in set(permutations(map(Fraction, cards))): # O(24)\n for (f1, f2, f3) in product(operators, repeat=3): # O(64)\n if f1(d, f2(c, f3(a, b))) == 24 or f1(f2(a, b), f3(c, d)) == 24: # O(2)\n return True\n return False\n```
2
1
[]
1
24-game
Python Backtracking
python-backtracking-by-mcmar-0eaf
Inspired by https://leetcode.com/problems/24-game/discuss/1062871/Python-dfs\nPlease check out and like his post.\nI just changed the ops handling to my preferr
mcmar
NORMAL
2021-06-23T02:50:40.877017+00:00
2021-06-23T02:50:40.877053+00:00
559
false
Inspired by https://leetcode.com/problems/24-game/discuss/1062871/Python-dfs\nPlease check out and like his post.\nI just changed the ops handling to my preferred method with fewer special cases.\nI was previously doing backtracking by deleting and inserting indexes back into the cards array. I like this more because it doesn\'t have any `O(n)` array operations.\n```\nops = [lambda a,b: a+b, lambda a,b: a*b, lambda a,b: a-b, lambda a,b: b-a, lambda a,b: a/b, lambda a,b: b/a]\n\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n def backtrack(n: int) -> bool:\n if n == 1:\n return abs(cards[0] - 24) < 0.01\n for i in range(n):\n a = cards[i]\n for j in range(i+1, n):\n b = cards[j]\n cards[j] = cards[n-1]\n for op in ops:\n try:\n cards[i] = op(a,b)\n if backtrack(n-1):\n return True\n except ZeroDivisionError:\n pass\n cards[j] = b\n cards[i] = a\n return False\n return backtrack(4)\n```
2
2
['Backtracking', 'Python']
1
24-game
Python solution
python-solution-by-dmyma-si2q
The main idea is to shorten the array by one operation in each iteration. Thus, we take first element from cards a and second from cards b, perform operation an
dmyma
NORMAL
2021-05-27T02:42:59.327665+00:00
2021-05-27T02:42:59.327702+00:00
258
false
The main idea is to shorten the array by one operation in each iteration. Thus, we take first element from cards `a` and second from cards `b`, perform operation and merge it with what is left.\n\n```\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n if len(cards) == 1: return abs(cards[0] - 24) < 0.1\n for i,a in enumerate(cards):\n for j,b in enumerate(cards):\n if i == j: continue\n left = [cards[k] for k in range(len(cards)) if k != i and k != j]\n for x in [a+b, a-b, a*b, b and a/b]:\n if self.judgePoint24(left+[x]): return True\n return False\n```
2
0
[]
2
24-game
Python Solution For Fun
python-solution-for-fun-by-mbylzy-digo
\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n ans=[[1, 1, 1, 8], [1, 1, 2, 6], [1, 1, 2, 7], [1, 1, 2, 8], [1, 1, 2, 9], [1,
mbylzy
NORMAL
2021-02-17T04:21:24.242321+00:00
2021-02-17T04:21:24.242375+00:00
247
false
```\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n ans=[[1, 1, 1, 8], [1, 1, 2, 6], [1, 1, 2, 7], [1, 1, 2, 8], [1, 1, 2, 9], [1, 1, 3, 4], [1, 1, 3, 5], [1, 1, 3, 6], [1, 1, 3, 7], [1, 1, 3, 8], [1, 1, 3, 9], [1, 1, 4, 4], [1, 1, 4, 5], [1, 1, 4, 6], [1, 1, 4, 7], [1, 1, 4, 8], [1, 1, 4, 9], [1, 1, 5, 5], [1, 1, 5, 6], [1, 1, 5, 7], [1, 1, 5, 8], [1, 1, 6, 6], [1, 1, 6, 8], [1, 1, 6, 9], [1, 1, 8, 8], [1, 2, 2, 4], [1, 2, 2, 5], [1, 2, 2, 6], [1, 2, 2, 7], [1, 2, 2, 8], [1, 2, 2, 9], [1, 2, 3, 3], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 3, 8], [1, 2, 3, 9], [1, 2, 4, 4], [1, 2, 4, 5], [1, 2, 4, 6], [1, 2, 4, 7], [1, 2, 4, 8], [1, 2, 4, 9], [1, 2, 5, 5], [1, 2, 5, 6], [1, 2, 5, 7], [1, 2, 5, 8], [1, 2, 5, 9], [1, 2, 6, 6], [1, 2, 6, 7], [1, 2, 6, 8], [1, 2, 6, 9], [1, 2, 7, 7], [1, 2, 7, 8], [1, 2, 7, 9], [1, 2, 8, 8], [1, 2, 8, 9], [1, 3, 3, 3], [1, 3, 3, 4], [1, 3, 3, 5], [1, 3, 3, 6], [1, 3, 3, 7], [1, 3, 3, 8], [1, 3, 3, 9], [1, 3, 4, 4], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 4, 7], [1, 3, 4, 8], [1, 3, 4, 9], [1, 3, 5, 6], [1, 3, 5, 7], [1, 3, 5, 8], [1, 3, 5, 9], [1, 3, 6, 6], [1, 3, 6, 7], [1, 3, 6, 8], [1, 3, 6, 9], [1, 3, 7, 7], [1, 3, 7, 8], [1, 3, 7, 9], [1, 3, 8, 8], [1, 3, 8, 9], [1, 3, 9, 9], [1, 4, 4, 4], [1, 4, 4, 5], [1, 4, 4, 6], [1, 4, 4, 7], [1, 4, 4, 8], [1, 4, 4, 9], [1, 4, 5, 5], [1, 4, 5, 6], [1, 4, 5, 7], [1, 4, 5, 8], [1, 4, 5, 9], [1, 4, 6, 6], [1, 4, 6, 7], [1, 4, 6, 8], [1, 4, 6, 9], [1, 4, 7, 7], [1, 4, 7, 8], [1, 4, 7, 9], [1, 4, 8, 8], [1, 4, 8, 9], [1, 5, 5, 5], [1, 5, 5, 6], [1, 5, 5, 9], [1, 5, 6, 6], [1, 5, 6, 7], [1, 5, 6, 8], [1, 5, 6, 9], [1, 5, 7, 8], [1, 5, 7, 9], [1, 5, 8, 8], [1, 5, 8, 9], [1, 5, 9, 9], [1, 6, 6, 6], [1, 6, 6, 8], [1, 6, 6, 9], [1, 6, 7, 9], [1, 6, 8, 8], [1, 6, 8, 9], [1, 6, 9, 9], [1, 7, 7, 9], [1, 7, 8, 8], [1, 7, 8, 9], [1, 7, 9, 9], [1, 8, 8, 8], [1, 8, 8, 9], [2, 2, 2, 3], [2, 2, 2, 4], [2, 2, 2, 5], [2, 2, 2, 7], [2, 2, 2, 8], [2, 2, 2, 9], [2, 2, 3, 3], [2, 2, 3, 4], [2, 2, 3, 5], [2, 2, 3, 6], [2, 2, 3, 7], [2, 2, 3, 8], [2, 2, 3, 9], [2, 2, 4, 4], [2, 2, 4, 5], [2, 2, 4, 6], [2, 2, 4, 7], [2, 2, 4, 8], [2, 2, 4, 9], [2, 2, 5, 5], [2, 2, 5, 6], [2, 2, 5, 7], [2, 2, 5, 8], [2, 2, 5, 9], [2, 2, 6, 6], [2, 2, 6, 7], [2, 2, 6, 8], [2, 2, 6, 9], [2, 2, 7, 7], [2, 2, 7, 8], [2, 2, 8, 8], [2, 2, 8, 9], [2, 3, 3, 3], [2, 3, 3, 5], [2, 3, 3, 6], [2, 3, 3, 7], [2, 3, 3, 8], [2, 3, 3, 9], [2, 3, 4, 4], [2, 3, 4, 5], [2, 3, 4, 6], [2, 3, 4, 7], [2, 3, 4, 8], [2, 3, 4, 9], [2, 3, 5, 5], [2, 3, 5, 6], [2, 3, 5, 7], [2, 3, 5, 8], [2, 3, 5, 9], [2, 3, 6, 6], [2, 3, 6, 7], [2, 3, 6, 8], [2, 3, 6, 9], [2, 3, 7, 7], [2, 3, 7, 8], [2, 3, 7, 9], [2, 3, 8, 8], [2, 3, 8, 9], [2, 3, 9, 9], [2, 4, 4, 4], [2, 4, 4, 5], [2, 4, 4, 6], [2, 4, 4, 7], [2, 4, 4, 8], [2, 4, 4, 9], [2, 4, 5, 5], [2, 4, 5, 6], [2, 4, 5, 7], [2, 4, 5, 8], [2, 4, 5, 9], [2, 4, 6, 6], [2, 4, 6, 7], [2, 4, 6, 8], [2, 4, 6, 9], [2, 4, 7, 7], [2, 4, 7, 8], [2, 4, 7, 9], [2, 4, 8, 8], [2, 4, 8, 9], [2, 4, 9, 9], [2, 5, 5, 7], [2, 5, 5, 8], [2, 5, 5, 9], [2, 5, 6, 6], [2, 5, 6, 7], [2, 5, 6, 8], [2, 5, 6, 9], [2, 5, 7, 7], [2, 5, 7, 8], [2, 5, 7, 9], [2, 5, 8, 8], [2, 5, 8, 9], [2, 6, 6, 6], [2, 6, 6, 7], [2, 6, 6, 8], [2, 6, 6, 9], [2, 6, 7, 8], [2, 6, 7, 9], [2, 6, 8, 8], [2, 6, 8, 9], [2, 6, 9, 9], [2, 7, 7, 8], [2, 7, 8, 8], [2, 7, 8, 9], [2, 8, 8, 8], [2, 8, 8, 9], [2, 8, 9, 9], [3, 3, 3, 3], [3, 3, 3, 4], [3, 3, 3, 5], [3, 3, 3, 6], [3, 3, 3, 7], [3, 3, 3, 8], [3, 3, 3, 9], [3, 3, 4, 4], [3, 3, 4, 5], [3, 3, 4, 6], [3, 3, 4, 7], [3, 3, 4, 8], [3, 3, 4, 9], [3, 3, 5, 5], [3, 3, 5, 6], [3, 3, 5, 7], [3, 3, 5, 9], [3, 3, 6, 6], [3, 3, 6, 7], [3, 3, 6, 8], [3, 3, 6, 9], [3, 3, 7, 7], [3, 3, 7, 8], [3, 3, 7, 9], [3, 3, 8, 8], [3, 3, 8, 9], [3, 3, 9, 9], [3, 4, 4, 4], [3, 4, 4, 5], [3, 4, 4, 6], [3, 4, 4, 7], [3, 4, 4, 8], [3, 4, 4, 9], [3, 4, 5, 5], [3, 4, 5, 6], [3, 4, 5, 7], [3, 4, 5, 8], [3, 4, 5, 9], [3, 4, 6, 6], [3, 4, 6, 8], [3, 4, 6, 9], [3, 4, 7, 7], [3, 4, 7, 8], [3, 4, 7, 9], [3, 4, 8, 9], [3, 4, 9, 9], [3, 5, 5, 6], [3, 5, 5, 7], [3, 5, 5, 8], [3, 5, 5, 9], [3, 5, 6, 6], [3, 5, 6, 7], [3, 5, 6, 8], [3, 5, 6, 9], [3, 5, 7, 8], [3, 5, 7, 9], [3, 5, 8, 8], [3, 5, 8, 9], [3, 5, 9, 9], [3, 6, 6, 6], [3, 6, 6, 7], [3, 6, 6, 8], [3, 6, 6, 9], [3, 6, 7, 7], [3, 6, 7, 8], [3, 6, 7, 9], [3, 6, 8, 8], [3, 6, 8, 9], [3, 6, 9, 9], [3, 7, 7, 7], [3, 7, 7, 8], [3, 7, 7, 9], [3, 7, 8, 8], [3, 7, 8, 9], [3, 7, 9, 9], [3, 8, 8, 8], [3, 8, 8, 9], [3, 8, 9, 9], [3, 9, 9, 9], [4, 4, 4, 4], [4, 4, 4, 5], [4, 4, 4, 6], [4, 4, 4, 7], [4, 4, 4, 8], [4, 4, 4, 9], [4, 4, 5, 5], [4, 4, 5, 6], [4, 4, 5, 7], [4, 4, 5, 8], [4, 4, 6, 8], [4, 4, 6, 9], [4, 4, 7, 7], [4, 4, 7, 8], [4, 4, 7, 9], [4, 4, 8, 8], [4, 4, 8, 9], [4, 5, 5, 5], [4, 5, 5, 6], [4, 5, 5, 7], [4, 5, 5, 8], [4, 5, 5, 9], [4, 5, 6, 6], [4, 5, 6, 7], [4, 5, 6, 8], [4, 5, 6, 9], [4, 5, 7, 7], [4, 5, 7, 8], [4, 5, 7, 9], [4, 5, 8, 8], [4, 5, 8, 9], [4, 5, 9, 9], [4, 6, 6, 6], [4, 6, 6, 7], [4, 6, 6, 8], [4, 6, 6, 9], [4, 6, 7, 7], [4, 6, 7, 8], [4, 6, 7, 9], [4, 6, 8, 8], [4, 6, 8, 9], [4, 6, 9, 9], [4, 7, 7, 7], [4, 7, 7, 8], [4, 7, 8, 8], [4, 7, 8, 9], [4, 7, 9, 9], [4, 8, 8, 8], [4, 8, 8, 9], [4, 8, 9, 9], [5, 5, 5, 5], [5, 5, 5, 6], [5, 5, 5, 9], [5, 5, 6, 6], [5, 5, 6, 7], [5, 5, 6, 8], [5, 5, 7, 7], [5, 5, 7, 8], [5, 5, 8, 8], [5, 5, 8, 9], [5, 5, 9, 9], [5, 6, 6, 6], [5, 6, 6, 7], [5, 6, 6, 8], [5, 6, 6, 9], [5, 6, 7, 7], [5, 6, 7, 8], [5, 6, 7, 9], [5, 6, 8, 8], [5, 6, 8, 9], [5, 6, 9, 9], [5, 7, 7, 9], [5, 7, 8, 8], [5, 7, 8, 9], [5, 8, 8, 8], [5, 8, 8, 9], [6, 6, 6, 6], [6, 6, 6, 8], [6, 6, 6, 9], [6, 6, 7, 9], [6, 6, 8, 8], [6, 6, 8, 9], [6, 7, 8, 9], [6, 7, 9, 9], [6, 8, 8, 8], [6, 8, 8, 9], [6, 8, 9, 9], [7, 8, 8, 9]]\n nums.sort()\n return nums in ans\n\t\t\n```
2
6
[]
1
24-game
12ms C++ solution using DFS
12ms-c-solution-using-dfs-by-ziplin-aa2p
\n vector<double> util(vector<double> a,vector<double> b){\n vector<double> r;\n for(int i=0;i<a.size();i++){\n for(int j=0;j<b.size
ziplin
NORMAL
2020-09-27T11:58:01.285912+00:00
2020-09-27T11:58:53.992971+00:00
387
false
```\n vector<double> util(vector<double> a,vector<double> b){\n vector<double> r;\n for(int i=0;i<a.size();i++){\n for(int j=0;j<b.size();j++){\n r.push_back(a[i]+b[j]);\n r.push_back(a[i]*b[j]);\n r.push_back(a[i]/b[j]);\n r.push_back(a[i]-b[j]);\n r.push_back(b[j]/a[i]);\n r.push_back(b[j]-a[i]);\n }\n }\n return r;\n }\n bool judgePoint24(vector<int>& n) {\n double epsilon=pow(10,-6);\n vector<double> a,b,c,x,y,z;\n bool f;\n for(int i=0;i<3;i++){\n for(int j=i+1;j<4;j++){\n a=util({(double)n[i]},{(double)n[j]});\n f=true;\n for(int k=0;k<4;k++){\n if(k!=i&&k!=j){\n if(f){\n b={(double)n[k]};\n f=false;\n }\n else c={(double)n[k]};\n }\n }\n x=util(a,util(b,c));\n y=util(util(a,b),c);\n z=util(util(a,c),b);\n for(int l=0;l<x.size();l++){\n if(abs(x[l]-24)<epsilon)return true;\n }\n for(int l=0;l<y.size();l++){\n if(abs(y[l]-24)<epsilon)return true;\n }\n for(int l=0;l<z.size();l++){\n if(abs(z[l]-24)<epsilon)return true;\n } \n }\n }\n return false;\n }\n```
2
0
['Depth-First Search', 'C']
0
24-game
Fast and Intuitive Java solution 2ms beats 86%
fast-and-intuitive-java-solution-2ms-bea-cpyv
The algorithm is simple, pick 2 values at a time, and try all possible combination of operators on it, and create a new array that you pass to the next recusive
yjin02
NORMAL
2020-09-20T01:22:01.104664+00:00
2020-09-20T01:22:25.981365+00:00
214
false
The algorithm is simple, pick 2 values at a time, and try all possible combination of operators on it, and create a new array that you pass to the next recusive call.\nif the array length is 1, we check to see if the number if 24\n\n```\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n double[] doubleArr = new double[nums.length];\n int index = 0;\n for (int num: nums) {\n doubleArr[index++] = num;\n }\n return dfs(doubleArr);\n }\n \n public boolean dfs(double[] nums) {\n if (nums.length == 1) {\n return Math.abs(24 - nums[0]) < 10e-5 ;\n }\n double[] newArr = new double[nums.length - 1];\n \n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < nums.length; j++) {\n if (i == j) continue;\n int index = 0;\n \n\t\t\t\t// put all the values we\'re not using yet into the array\n for (int z = 0; z < nums.length; z++) {\n if (z == i || z == j) continue;\n newArr[index++] = nums[z];\n }\n\t\t\t\t\n\t\t\t\t//Try all combinations\n newArr[index] = nums[i] - nums[j];\n if (dfs(newArr)) return true;\n \n newArr[index] = nums[j] - nums[i];\n if (dfs(newArr)) return true;\n \n newArr[index] = nums[i] * nums[j];\n if (dfs(newArr)) return true;\n \n newArr[index] = nums[i] + nums[j];\n if (dfs(newArr)) return true;\n \n if (nums[j] != 0) {\n newArr[index] = nums[i] / nums[j];\n if (dfs(newArr)) return true;\n }\n \n if (nums[i] != 0) {\n newArr[index] = nums[j] / nums[i];\n if (dfs(newArr)) return true;\n }\n }\n }\n return false;\n }\n}\n```
2
0
[]
0
24-game
Self Explaintory
self-explaintory-by-anmolgera-yfho
\n\n\nclass Solution {\npublic:\n bool judgePoint24(vector& nums) {\n \n sort(nums.begin(), nums.end());\n do {\n if (valid(nu
anmolgera
NORMAL
2020-08-03T02:18:51.457007+00:00
2020-08-03T02:18:51.457070+00:00
173
false
\n\n\nclass Solution {\npublic:\n bool judgePoint24(vector<int>& nums) {\n \n sort(nums.begin(), nums.end());\n do {\n if (valid(nums)) return true;\n } while(next_permutation(nums.begin(), nums.end()));\n return false;\n }\n\n bool valid(vector<int>& nums) {\n double a = nums[0], b = nums[1], c = nums[2], d = nums[3];\n if (valid(a+b, c, d) || valid(a-b, c, d) || valid(a*b, c, d) ||b&& valid(a/b, c, d)) return true;\n if (valid(a, b+c, d) || valid(a, b-c, d) || valid(a, b*c, d) || c&&valid(a, b/c, d)) return true;\n if (valid(a, b, c+d) || valid(a, b, c-d) || valid(a, b, c*d) || d&& valid(a, b, c/d)) return true;\n return false;\n }\n bool valid(double a, double b, double c) {\n if (valid(a+b, c) || valid(a-b, c) || valid(a*b, c) || b&&valid(a/b, c)) return true;\n if (valid(a, b+c) || valid(a, b-c) || valid(a, b*c) || c&&valid(a, b/c)) return true;\n return false;\n }\n bool valid(double a, double b) {\n if (abs(a+b-24.0) < 0.0001 || abs(a-b-24.0) < 0.0001 || abs(a*b-24.0) < 0.0001 || b&&abs(a/b-24.0) < 0.0001) \n return true;\n return false;\n }\n \n \n};
2
0
[]
2
24-game
Java arrays only - no lists, faster than 85%
java-arrays-only-no-lists-faster-than-85-qcas
```\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n double[] d = new double[nums.length];\n for (int i=0; i 23.9999999999999 &&
likhvarev
NORMAL
2020-05-25T06:58:19.574393+00:00
2020-05-25T06:58:19.574440+00:00
217
false
```\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n double[] d = new double[nums.length];\n for (int i=0; i<nums.length; i++) {\n d[i] = nums[i];\n }\n return check(d);\n }\n \n private boolean check(double[] nums) {\n if (nums.length == 1) {\n return nums[0] > 23.9999999999999 && nums[0] < 24.0000000000001;\n }\n for (int i=0; i<nums.length; i++) {\n for (int j=0; j<nums.length; j++) {\n if (i==j) continue;\n double a = nums[i];\n double b = nums[j];\n if (check(copy(nums, i, j, a*b)) \n || check(copy(nums, i, j, a/b))\n || check(copy(nums, i, j, a+b))\n || check(copy(nums, i, j, a-b))) {\n return true;\n }\n }\n }\n return false;\n }\n \n private double[] copy(double[] nums, int skip1, int skip2, double newNum) {\n double[] copy = new double[nums.length-1];\n for (int i=0, j=0; i<nums.length; i++) {\n if (i==skip1 || i==skip2) continue;\n copy[j++] = nums[i];\n }\n copy[copy.length-1] = newNum;\n return copy;\n }\n}
2
0
[]
1
24-game
Java no control flow (no if, for, while, etc.), beats 100% time, 100% space
java-no-control-flow-no-if-for-while-etc-xrmd
With only 4 inputs this problem can be solved with basically only booleans and math operations.\n\nThis code doesn\'t make any assumptions about the inputs bein
glxxyz
NORMAL
2020-04-18T05:52:56.525952+00:00
2020-04-18T19:12:33.949370+00:00
650
false
With only 4 inputs this problem can be solved with basically only booleans and math operations.\n\nThis code doesn\'t make any assumptions about the inputs being in the range 1-9, they could be any integers and it would still work fine- the solutions that encode all possible answers only work with 1-9 inputs.\n\nThis solution does a bunch of unecessary operations (e.g. calculates both ```a * b``` and ```b * a``` but with no control flow it just blazes through the calculations and doesn\'t worry about it. \n\nI tried inlining most of the methods here, and for some reason that made things a lot slower: https://leetcode.com/problems/24-game/discuss/584772/Java-bringing-new-meaning-to-brute-force\n\n```\n/*\n\nRuntime: 0 ms, faster than 100.00% of Java online submissions for 24 Game.\nMemory Usage: 36.5 MB, less than 100.00% of Java online submissions for 24 Game.\n\n*/\n\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n\n double a = Double.valueOf(nums[0]);\n double b = Double.valueOf(nums[1]);\n double c = Double.valueOf(nums[2]);\n double d = Double.valueOf(nums[3]);\n \n return judge(a, b, c, d)\n || judge(a, b, d, c)\n || judge(a, c, b, d)\n || judge(a, c, d, b)\n || judge(a, d, b, c)\n || judge(a, d, c, b)\n || judge(b, a, c, d)\n || judge(b, a, d, c)\n || judge(b, c, a, d)\n || judge(b, c, d, a)\n || judge(b, d, a, c)\n || judge(b, d, c, a)\n || judge(c, a, b, d)\n || judge(c, a, d, b)\n || judge(c, b, a, d)\n || judge(c, b, d, a)\n || judge(c, d, a, b)\n || judge(c, d, b, a)\n || judge(d, a, b, c)\n || judge(d, a, c, b)\n || judge(d, b, a, c)\n || judge(d, b, c, a)\n || judge(d, c, a, b)\n || judge(d, c, b, a);\n }\n \n private boolean judge(double a, double b, double c, double d) {\n return judge(a, b, c*d)\n || judge(a, b, c+d)\n || judge(a, b, c-d)\n || d != 0 && judge(a, b, c/d);\n }\n\n private boolean judge(double a, double b, double c) {\n return judge3(a, b, c)\n || judge3(a, c, b)\n || judge3(b, a, c)\n || judge3(b, c, a)\n || judge3(c, a, b)\n || judge3(c, b, a);\n } \n\n private boolean judge3(double a, double b, double c) {\n return judge(a, b*c)\n || judge(a, b+c)\n || judge(a, b-c)\n || c != 0 && judge(a, b/c);\n } \n\n private boolean judge(double a, double b) {\n return judge(a*b)\n || judge(a+b)\n || judge(a-b)\n || b != 0 && judge(a/b);\n } \n\n private boolean judge(double a) {\n return Math.abs(a - 24) < 0.000001;\n }\n}\n```
2
2
['Java']
1
24-game
Easy to understand recursive JAVA solution
easy-to-understand-recursive-java-soluti-oo05
\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n List<Double> list = new ArrayList<>();\n for (int num : nums) list.add((double
legendaryengineer
NORMAL
2020-03-31T21:09:55.470105+00:00
2020-03-31T21:09:55.470139+00:00
259
false
```\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n List<Double> list = new ArrayList<>();\n for (int num : nums) list.add((double) num);\n return can(list);\n }\n \n private boolean can(List<Double> list) {\n if (list.size() == 1) return (Math.abs(list.get(0) - 24.0) < 0.001);\n for (int i = 0; i < list.size(); i++) {\n for (int j = i + 1; j < list.size(); j++) {\n List<Double> combined = new ArrayList<>();\n combined.add(list.get(i) + list.get(j));\n combined.add(list.get(i) - list.get(j));\n combined.add(list.get(j) - list.get(i));\n combined.add(list.get(i) * list.get(j));\n combined.add(list.get(i) / list.get(j));\n combined.add(list.get(j) / list.get(i));\n List<Double> rest = new ArrayList<>();\n for (int k = 0; k < list.size(); k++) {\n if (k != i && k != j) rest.add(list.get(k));\n }\n for (int l = 0; l < combined.size(); l++) {\n rest.add(combined.get(l));\n if (can(rest)) return true;\n rest.remove(rest.size() - 1);\n }\n }\n }\n return false;\n }\n}\n```
2
0
[]
2
24-game
Javascript and Python
javascript-and-python-by-andyoung-6cye
Idea\n1. recursively try every pair of nums[i] and nums[j], with rest numbers from nums\n\nJavascript\njs\nvar judgePoint24 = function(nums) {\n if (nums.len
andyoung
NORMAL
2020-03-08T04:15:24.385612+00:00
2020-03-08T19:33:30.388163+00:00
451
false
**Idea**\n1. recursively try every pair of `nums[i]` and `nums[j]`, with rest numbers from `nums`\n\n**Javascript**\n```js\nvar judgePoint24 = function(nums) {\n if (nums.length == 1) {\n return Math.abs(nums[0] - 24) < 0.01;\n }\n\n let ans = false;\n for (let i = 0; i < nums.length; ++i) {\n for (let j = 0; j < i; ++j) {\n // grab other numbers\n const rest = [];\n for (let k = 0; k < nums.length; ++k) {\n if (k != i && k != j) {\n rest.push(nums[k]);\n }\n }\n // list all possibilities\n const target = [\n nums[i] + nums[j], nums[i] - nums[j],\n nums[j] - nums[i], nums[i] * nums[j]\n ];\n if (nums[i]) target.push(nums[j] / nums[i]);\n if (nums[j]) target.push(nums[i] / nums[j]);\n // try next round with less numbers\n for (const t of target) {\n ans = ans || judgePoint24([t, ...rest]);\n if (ans) return true;\n }\n }\n }\n return ans;\n};\n```\n\n**Python**\n```python\ndef judgePoint24(self, nums):\n\tif len(nums) == 1:\n\t\treturn abs(nums[0] - 24) < 0.01\n\n\tans = False\n\tfor i in range(len(nums)):\n\t\tfor j in range(i):\n\t\t\trest = []\n\t\t\tfor k in range(len(nums)):\n\t\t\t\tif k != i and k != j:\n\t\t\t\t\trest.append(nums[k])\n\t\t\ttarget = [\n\t\t\t\tnums[i] + nums[j], nums[i] - nums[j],\n\t\t\t\tnums[j] - nums[i], nums[i] * nums[j]\n\t\t\t]\n\t\t\tif nums[i]:\n\t\t\t\ttarget.append(nums[j] / float(nums[i]))\n\t\t\tif nums[j]:\n\t\t\t\ttarget.append(nums[i] / float(nums[j]))\n\t\t\tfor t in target:\n\t\t\t\tans = ans or self.judgePoint24(rest[:] + [t])\n\t\t\t\tif ans:\n\t\t\t\t\treturn True\n\treturn ans\n```
2
1
['Python', 'JavaScript']
1
24-game
Swift solution
swift-solution-by-zzhenia-9vs0
The code below is a simple implementation of the solution provided to the problem with the following stats:\n\n> Runtime: 220 ms, faster than 10.53% of Swift on
zzhenia
NORMAL
2020-02-24T17:37:35.960005+00:00
2020-02-24T17:37:35.960049+00:00
224
false
The code below is a simple implementation of the solution provided to the problem with the following stats:\n\n> Runtime: 220 ms, faster than 10.53% of Swift online submissions for 24 Game.\nMemory Usage: 21.1 MB, less than 100.00% of Swift online submissions for 24 Game.\n\nI wonder how could I make it faster and what are those 90% of Swift solutions which beat mine.\n\n```\nclass Solution {\n let precision = 1e-3\n let seeked = 24.0\n \n func judgePoint24(_ nums: [Int]) -> Bool {\n return judgePoint24(nums.map({ Double($0) }))\n }\n \n func judgePoint24(_ nums: [Double]) -> Bool {\n if nums.count == 1 {\n return nums[0] >= seeked - precision && nums[0] <= seeked + precision\n }\n for i in 0..<nums.count {\n for j in 0..<nums.count {\n if i == j {\n continue\n }\n var nums_ = nums.enumerated().filter({ $0.0 != i && $0.0 != j }).map({ $0.1 })\n let parts = possibleParts(a: nums[i], b: nums[j])\n for p in parts {\n nums_.append(p)\n if judgePoint24(nums_) {\n return true\n }\n nums_ = nums_.dropLast()\n }\n }\n }\n return false\n }\n \n private func possibleParts(a: Double, b: Double) -> [Double] {\n var res = [a + b, a - b, a * b]\n if a != 0 {\n res.append(b / a)\n }\n return res\n }\n}\n```
2
0
['Swift']
1
24-game
Python straightforward recursive solution
python-straightforward-recursive-solutio-snf8
\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return abs(nums[0] - 24) < 10**-3\n for
tsuai
NORMAL
2019-12-02T08:21:15.891063+00:00
2019-12-02T08:21:15.891101+00:00
315
false
```\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return abs(nums[0] - 24) < 10**-3\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n add = nums[i] + nums[j]\n minus = nums[i] - nums[j]\n time = nums[i] * nums[j]\n nl = nums[:i] + nums[i + 1:j] + nums[j + 1:]\n res = self.judgePoint24(nl + [add]) or self.judgePoint24(nl + [minus]) or self.judgePoint24(nl + [time]) or self.judgePoint24(nl + [-minus])\n if nums[j] != 0 and nums[i] != 0:\n divide = nums[i] / nums[j]\n res = res or self.judgePoint24(nl + [divide]) or self.judgePoint24(nl + [1/divide])\n if res:\n return True\n return False\n```\nWe pick every pair of numbers available in current array, try all 4 calculations on the pair, and replace this pair with the result. Then recursively call this function with the new array. The base case is when there is only one number in the array. In this case we check if that number is 24.
2
0
[]
0
24-game
Python beats 95%
python-beats-95-by-etherwei-ishc
Python seems to have float precision problem so we need to manually check the returned results.\nUsing set to filter out duplicate numbers.\n\n def judgePoin
etherwei
NORMAL
2019-07-12T04:50:20.369996+00:00
2019-07-12T04:50:20.370029+00:00
465
false
Python seems to have float precision problem so we need to manually check the returned results.\nUsing set to filter out duplicate numbers.\n```\n def judgePoint24(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n\n def helper(start, end, arr):\n if start == end:\n return [arr[start]]\n results = set()\n for i in range(start, end):\n left = helper(start, i, arr)\n right = helper(i + 1, end, arr)\n\n for l in left:\n for r in right:\n results.add(l + r)\n results.add(l * r)\n if r != 0:\n results.add(l / float(r))\n results.add(l - r)\n return results\n\n def check(s):\n for val in s:\n if abs(val - 24) < 0.0002:\n return True\n\n import itertools\n for arr in itertools.permutations(nums):\n if check(helper(0, 3, arr)):\n return True\n return False\n```
2
0
[]
0
24-game
Simple Java solution beats 100%
simple-java-solution-beats-100-by-karayv-n0mc
\n public boolean judgePoint24(int[] nums) {\n double[] dbls = new double[nums.length];\n for (int i = 0; i < nums.length; i++) dbls[i] = (doub
karayv
NORMAL
2019-03-31T07:22:53.457037+00:00
2019-03-31T07:22:53.457104+00:00
309
false
```\n public boolean judgePoint24(int[] nums) {\n double[] dbls = new double[nums.length];\n for (int i = 0; i < nums.length; i++) dbls[i] = (double) nums[i];\n return solve(dbls);\n }\n\n private boolean solve(double[] dbls) {\n if (dbls.length == 1) {\n return Math.abs(dbls[0] - 24.0) <= .0000000000001;\n }\n double[] nextDbls = new double[dbls.length - 1];\n for (int i1 = 1; i1 < dbls.length; i1++) {\n for (int i2 = 0; i2 < i1; i2++) {\n fill(dbls, nextDbls, i1, i2);\n \n nextDbls[0] = dbls[i1] + dbls[i2];\n if (solve(nextDbls)) return true;\n\n nextDbls[0] = dbls[i1] - dbls[i2];\n if (solve(nextDbls)) return true;\n\n nextDbls[0] = dbls[i2] - dbls[i1];\n if (solve(nextDbls)) return true;\n\n nextDbls[0] = dbls[i1] * dbls[i2];\n if (solve(nextDbls)) return true;\n\n nextDbls[0] = dbls[i1] / dbls[i2];\n if (dbls[i2] != 0 && solve(nextDbls)) return true;\n\n nextDbls[0] = dbls[i2] / dbls[i1];\n if (dbls[i1] != 0 && solve(nextDbls)) return true;\n }\n }\n return false;\n }\n```
2
0
[]
0
24-game
Java recursive easy to read
java-recursive-easy-to-read-by-lootshen-ayj8
\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n double[] doubles = new double[4];\n for (int i = 0; i < 4; i++) {\n
lootshen
NORMAL
2019-03-26T18:40:12.759126+00:00
2019-03-26T18:40:12.759192+00:00
239
false
```\nclass Solution {\n public boolean judgePoint24(int[] nums) {\n double[] doubles = new double[4];\n for (int i = 0; i < 4; i++) {\n doubles[i] = nums[i] / 1.0;\n }\n return dfs(doubles);\n }\n\n public boolean dfs(double[] nums) {\n int n = nums.length;\n if (n==1 && Math.abs(nums[0] - 24.0) < 1e-6)\n return true;\n double[] left = new double[n-1];\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n for (int k = 0, l = 0; k < n; k++) {\n if (k != i && k != j) {\n left[l] = nums[k];\n l++;\n }\n }\n double a = nums[i], b = nums[j];\n left[n-2] = a + b; if (dfs(left)) return true;\n left[n-2] = a * b; if (dfs(left)) return true;\n left[n-2] = a - b; if (dfs(left)) return true;\n left[n-2] = a / b; if (dfs(left)) return true;\n left[n-2] = b - a; if (dfs(left)) return true;\n left[n-2] = b / a; if (dfs(left)) return true;\n }\n }\n return false;\n }\n}\n```
2
1
[]
0