B站 8.13后端开发笔试
第一题 24点
暴力
public class BiliBili_1 {
public boolean Game24Points (int[] arr) {
boolean [] used = new boolean [4];
return helper(arr, used, 0.0);
}
private boolean helper(int[] arr, boolean[] used, double res){
for (int i = 0; i < arr.length; i++) {
if(used[i] == false){
used[i] = true;
if(helper(arr, used, res + arr[i]) || helper(arr, used, res - arr[i]) || helper(arr, used, res * arr[i]) || helper(arr, used, res / arr[i])){
return true;
}
used[i] = false;
}
}
if(res == 24){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
int [] arr = new int [] {7, 2, 1, 10};
boolean b = new BiliBili_1().Game24Points(arr);
System.out.println(b);
}
}
第二题 LeetCode 20原题
public class Bilibili_2 {
public boolean IsValidExp (String s) {
Map<Character, Character> hm = new HashMap<>();
hm.put(')','(');
hm.put('}','{');
hm.put(']','[');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(hm.containsKey(c)){
char top = stack.isEmpty() ? '*' : stack.pop();
if(top != hm.get(c)){
}
}else{
stack.push(c);
} return false;
}
return stack.isEmpty();
}
}
第三题 背包
public class Bilibili_3 {
public int GetCoinCount (int N) {
int remainder = 1024 - N;
int [] dp = new int [remainder + 1];
int [] coins = new int []{1, 4, 16, 64};
for (int i = 0; i <= remainder; i++) {
dp[i] = i;
}
for (int i = 0; i < 4; i++) {
for(int j = coins[i]; j <= remainder; j++){
dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
}
}
return dp[remainder];
}
public static void main(String[] args) {
int i = new Bilibili_3().GetCoinCount(200);
System.out.println(i);
}
}