五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網 會員登陸 & 注冊

dfs/重新排列得到2的冪

2021-10-28 18:17 作者:劍離我離  | 我要投稿

869 重新排列得到2的冪

出現問題:當使用i=start+1的方式進行傳參時,并不能搜索出一些結果。例如:46 變不成64,需要使用vis數組進行標記的方式才可以:

官方:class Solution { ? ?boolean[] vis; ? ?public boolean reorderedPowerOf2(int n) { ? ? ? ?char[] nums = Integer.toString(n).toCharArray(); ? ? ? ?Arrays.sort(nums); ? ? ? ?vis = new boolean[nums.length]; ? ? ? ?return backtrack(nums, 0, 0); ? ?} ? ?public boolean backtrack(char[] nums, int idx, int num) { ? ? ? ?if (idx == nums.length) { ? ? ? ? ? ?return isPowerOfTwo(num); ? ? ? ?} ? ? ? ?for (int i = 0; i < nums.length; ++i) { ? ? ? ? ? ?// 不能有前導零 ? ? ? ? ? ?if ((num == 0 && nums[i] == '0') || vis[i] || (i > 0 && !vis[i - 1] && nums[i] == nums[i - 1])) { ? ? ? ? ? ? ? ?continue; ? ? ? ? ? ?} ? ? ? ? ? ?vis[i] = true; ? ? ? ? ? ?if (backtrack(nums, idx + 1, num * 10 + nums[i] - '0')) { ? ? ? ? ? ? ? ?return true; ? ? ? ? ? ?} ? ? ? ? ? ?vis[i] = false; ? ? ? ?} ? ? ? ?return false; ? ?} ? ?public boolean isPowerOfTwo(int n) { ? ? ? ?return (n & (n - 1)) == 0; ? ?} }三葉:bfs 首先用靜態(tài)代碼塊對set進行了預處理,然后將數值映射到一個數組上(非字符串的方式),這樣就可以知道哪個數字出現多少次了class Solution { ? ?static Set<Integer> set = new HashSet<>(); ? ?static { ? ? ? ?for (int i = 1; i < (int)1e9+10; i *= 2) set.add(i); ? ?} ? ?int m; ? ?int[] cnts = new int[10]; ? ?public boolean reorderedPowerOf2(int n) { ? ? ? ?while (n != 0) { //對數字進行映射 ? ? ? ? ? ?cnts[n % 10]++; ? ? ? ? ? ?n /= 10; ? ? ? ? ? ?m++; ? ? ? ?} ? ? ? ?return dfs(0, 0); ? ?} ? ?boolean dfs(int u, int cur) { ? ? ? ?if (u == m) return set.contains(cur); ? ? ? ?for (int i = 0; i < 10; i++) { ? ? ? ? ? ?if (cnts[i] != 0) {//迷宮表的方式 ? ? ? ? ? ? ? ?cnts[i]--; ? ? ? ? ? ? ? ?if ((i != 0 || cur != 0) && dfs(u + 1, cur * 10 + i)) return true; ? ? ? ? ? ? ? ?//cur*10+i cur*10 因為整個數值加了一位,所以要乘10 ,而i對應的就是現在cnts存有數字的情況(>0) ? ? ? ? ? ? ? ?cnts[i]++; //回溯 ? ? ? ? ? ?} ? ? ? ?} ? ? ? ?return false; ? ?} }打表 + 詞頻統(tǒng)計class Solution { ? ?static Set<Integer> set = new HashSet<>(); ? ?static { ? ? ? ?for (int i = 1; i < (int)1e9+10; i *= 2) set.add(i); ? ?} ? ?public boolean reorderedPowerOf2(int n) { ? ? ? ?int[] cnts = new int[10]; ? ? ? ?while (n != 0) { ? ? ? ? ? ?cnts[n % 10]++; ? ? ? ? ? ?n /= 10; ? ? ? ?} ? ? ? ?int[] cur = new int[10]; ? ? ? ?out:for (int x : set) { ? ? ? ? ? ?Arrays.fill(cur, 0); ? ? ? ? ? ?while (x != 0) { ? ? ? ? ? ? ? ?cur[x % 10]++; ? ? ? ? ? ? ? ?x /= 10; ? ? ? ? ? ?} ? ? ? ? ? ?for (int i = 0; i < 10; i++) { ? ? ? ? ? ? ? ?if (cur[i] != cnts[i]) continue out; ? ? ? ? ? ?} ? ? ? ? ? ?return true; ? ? ? ?} ? ? ? ?return false; ? ?} }


dfs/重新排列得到2的冪的評論 (共 條)

分享到微博請遵守國家法律
丰城市| 富蕴县| 彭泽县| 石阡县| 黄骅市| 松阳县| 临湘市| 云南省| 千阳县| 麦盖提县| 河东区| 新巴尔虎右旗| 洱源县| 天水市| 海原县| 深水埗区| 盐池县| 高陵县| 区。| 仁怀市| 年辖:市辖区| 靖边县| 康定县| 荣昌县| 饶河县| 微博| 班戈县| 广水市| 萝北县| 恩施市| 长武县| 汤阴县| 晋州市| 西林县| 平阳县| 布尔津县| 定陶县| 于田县| 桐乡市| 玉山县| 石河子市|