来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reordered-power-of-2
题目描述:
给定正整数 N ,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。
如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false。
示例 1:
输入:1
输出:true
示例 2:
输入:10
输出:false
示例 3:
输入:16
输出:true
示例 4:
输入:24
输出:false
示例 5:
输入:46
输出:true
思路:
- 先将范围内所有2的幂提前初始化到容器set中
- 深度遍历n到所有组合,判断是否存在于set中
- 是,返回true
- 否,返回false
代码实现:
class Solution {
public Set<Integer> set = new HashSet();
public int len;
public boolean[] flag;
public boolean result = false;
public String str_num;
public boolean reorderedPowerOf2(int n) {
str_num = String.valueOf(n);
// 数字长度.
len = str_num.length();
flag = new boolean[len];
for (int i = 1; i <= (int)1e9+10; i *= 2) {
set.add(i);
}
for (int i = 0; i < len; i++) {
char ch = str_num.charAt(i);
if (ch == '0') continue;
flag[i] = true;
StringBuilder sb = new StringBuilder();
sb.append(ch + "");
dfs(0, sb);
flag[i] = false;
sb.deleteCharAt(sb.length() - 1);
}
return result;
}
public void dfs(int idx, StringBuilder sb) {
if (idx == (len - 1)) {
Integer num = Integer.valueOf(sb.toString());
if (set.contains(num)) result = true;
return;
}
for (int i = 0; i < len; i++) {
if (flag[i]) continue;
char ch = str_num.charAt(i);
sb.append(ch + "");
flag[i] = true;
dfs (idx + 1, sb);
sb.deleteCharAt(sb.length() - 1);
flag[i] = false;
}
}
}
网友评论