第一题用的暴力方法,没想到一次性过了
package duxiaoman1;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int k = cin.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = cin.nextInt();
}
int cnt = 0;
for (int i = 0; i < n; i++) {
int minVal = Integer.MAX_VALUE;
int maxVal = Integer.MIN_VALUE;
for (int j = i; j < n; j++) {
minVal = Math.min(minVal, nums[j]);
maxVal = Math.max(maxVal, nums[j]);
if (maxVal == k * minVal)
cnt++;
}
}
System.out.println(cnt);
}
}
第二题也是用DFS暴力搜索,也是一次性过了,还以为会超时呢
package duxiaoman2;
import java.util.Scanner;
public class Main {
static boolean found = false;
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int T = cin.nextInt();
for (int p = 0; p < T; p++) {
int n = cin.nextInt();
int m = cin.nextInt();
int k = cin.nextInt();
int x = cin.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
grid[i][j] = cin.nextInt();
}
}
if (hasSumEqualK(grid, n, m, k, x))
System.out.println("yes");
else
System.out.println("no");
}
}
public static boolean hasSumEqualK(int[][] grid, int n, int m,
int k, int x) {
found = false;
dfs(grid, n, m, 0, 0, 0, x);
return found;
}
public static void dfs(int[][] grid, int n, int m,
int i, int j, int sum, int x) {
sum += grid[i][j];
if (sum == x && i == n - 1 && j == m - 1) {
found = true;
return;
}
if (i + 1 < n) {
dfs(grid, n, m, i + 1, j, sum, x);
}
if (found)
return;
if (j + 1 < m) {
dfs(grid, n, m, i, j + 1, sum, x);
}
}
}
第三题不会,总是超时,有大佬能分享下解法吗
#度小满笔试#