最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

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

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的冪的評論 (共 條)

分享到微博請遵守國家法律
德化县| 南澳县| 三河市| 年辖:市辖区| 类乌齐县| 金秀| 东明县| 江北区| 大连市| 冕宁县| 宁武县| 岑溪市| 罗平县| 桓仁| 平邑县| 章丘市| 洛隆县| 牙克石市| 柯坪县| 昌宁县| 文山县| 梅州市| 师宗县| 保康县| 时尚| 黄陵县| 合水县| 淳安县| 横峰县| 建平县| 阿拉善右旗| 峡江县| 南溪县| 香港 | 驻马店市| 玉林市| 武隆县| 阳东县| 巴彦淖尔市| 洞头县| 沂源县|