Quellcode durchsuchen

#feat:leetcode p1780题题解

yangyi vor 2 Wochen
Ursprung
Commit
3e7211728f
2 geänderte Dateien mit 84 neuen und 0 gelöschten Zeilen
  1. 63 0
      src/leetcode/p1780/Solution.java
  2. 21 0
      src/leetcode/p1780/SolutionTest.java

+ 63 - 0
src/leetcode/p1780/Solution.java

@@ -0,0 +1,63 @@
+package leetcode.p1780;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2025/8/14 13:01
+ * @Description: https://leetcode.cn/problems/check-if-number-is-a-sum-of-powers-of-three/description/
+ * 1780. 判断一个数字是否可以表示成三的幂的和
+ */
+class Solution {
+    public boolean checkPowersOfThree(int n) {
+        List<Long> list = new ArrayList<>();
+        long current = 1L;
+        while (current <= n) {
+            list.add(current);
+            current *= 3;
+        }
+        //缓存
+        boolean[][] memory = new boolean[list.size()+1][n+1];
+        boolean[][] f = new boolean[list.size()+1][n+1];
+        return dfs(0,n,list,memory,f);
+    }
+
+    private boolean dfs(int i, long n,List<Long> list,boolean[][] memory,boolean[][] f) {
+        if(n == 0) return true;
+        //记忆化搜索
+        if (f[i][(int)n]) return memory[i][(int)n];
+        if(i >= list.size()) return false;
+        boolean flag = false;
+        //选
+        if(list.get(i) <= n){
+            flag = flag || dfs(i+1,n - list.get(i),list, memory,f);
+        }
+        //不选
+        flag = flag || dfs(i+1,n,list, memory,f);
+        //缓存
+        f[i][(int)n] = true;
+        memory[i][(int)n] = flag;
+        return flag;
+    }
+
+    /**
+     * @param n
+     * @return boolean
+     * @description: 灵茶山艾府的题解做法,三进制思考
+     * @author: 杨逸
+     * @data:2025/08/14 13:48:04
+     * @since 1.0.0
+     */
+    public boolean checkPowersOfThree1(int n) {
+        while (n > 0) {
+            if (n % 3 == 2) {
+                return false;
+            }
+            n /= 3;
+        }
+        return true;
+    }
+}

+ 21 - 0
src/leetcode/p1780/SolutionTest.java

@@ -0,0 +1,21 @@
+package leetcode.p1780;
+
+import org.junit.Test;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2025/8/14 13:15
+ * @Description:
+ */
+public class SolutionTest {
+
+    @Test
+    public void checkPowersOfThree() {
+        int n = 12;
+        Solution solution = new Solution();
+        boolean result = solution.checkPowersOfThree(n);
+        System.out.println(result);
+    }
+}