From eff1a8f638d756b1f95fbc62a7247ab4343a358a Mon Sep 17 00:00:00 2001 From: "Duc M. Quoc" Date: Wed, 29 Jan 2025 23:09:48 +0700 Subject: [PATCH] Create 2992-2.java efficient DP passed all testcases (12/12) --- .../2992-2.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 solutions/2992. Number of Self-Divisible Permutations/2992-2.java diff --git a/solutions/2992. Number of Self-Divisible Permutations/2992-2.java b/solutions/2992. Number of Self-Divisible Permutations/2992-2.java new file mode 100644 index 00000000000..5f5444b501e --- /dev/null +++ b/solutions/2992. Number of Self-Divisible Permutations/2992-2.java @@ -0,0 +1,26 @@ +class Solution { + public int selfDivisiblePermutationCount(int n) { + int s = 1 << n; + int[][] dp = new int[n + 1][s]; + dp[0][0] = 1; + for (int i = 1; i <= n; i++) { + for (int state = 0; state < (s); state++) { + for (int d = 1; d <= n; d++) { + if (gcd(d, i) != 1) { + continue; + } + if (((state >> (d - 1)) & 1) == 0) { + continue; + } + dp[i][state] += dp[i - 1][state - (1 << (d - 1))]; + } + } + } + + return dp[n][(s) - 1]; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +}