while(scanner.hasNext()){
String str= scanner.nextLine();
char[] chars= str.toCharArray();
Arrays.sort(chars);
for(char c :chars ){
System.out.print©;
}
System.out.println();
}
这个是说输入可能包含很多行,不能仅判断一行,需要逐行判断,并且打印的输出也要保证跳到下一行。
nextLine方法是得到这一行光标后面的字符串并且切换光标到下一行,如果前面用了nextInt之类的就必须使用一次使光标移到下一行再读取。
next方法获取下一个字符串,一般用nextInt比较多。
while(in.hasNext()){}这个东西会经常用到,因为题库里面说了输入什么,但是它可能会输入很多组输入案例并且不在题目里面告诉我们,需要再最外层逻辑加上这个。
8.18三道机试题都是回溯(也可以叫深度优先搜索)题,一个是背包问题,一个是下面这个,三道都需要做优化才能高分,可惜只优化了一道。看牛客说有两道就是背包问题。
一个整数数组,求有多少个组合满足和为一个定值,这里需要得高分应该是必须用动态规划或者记忆化回溯。个人感觉回溯比dp简单很多,下面容易错的一个地方是要先判断target==0的情况再看start 是否越界。因为这种情况就是最后一个数字等于target的情况,这时是有一个解的。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int target = scanner.nextInt();
int n = scanner.nextInt();
List<Integer> list = new ArrayList<>();
boolean flag = false;
for (int i = 0; i < n; i++) {
int e = scanner.nextInt();
list.add(e);
if (target >= e) {
flag = true;
}
}
if (!flag) {
System.out.println(-1);
continue;
}
int res = getNum(target, n, list);
System.out.println(res);
}
}
private static int getNum(int target, int n, List<Integer> list) {
int res = dfs(target, list, 0);
return res;
}
static Map<Pair<Integer, Integer>, Integer> map = new HashMap<>();
static int dfs(int target, List<Integer> list, int start) {
Pair<Integer, Integer> key = new Pair<>(target, start);
if (map.containsKey(key)) {
return map.get(key);
}
//start超出也没有关系
if (target == 0) {
map.put(key, 1);
return 1;
}
if (target < 0 || start >= list.size()) {
map.put(key, 0);
return 0;
}
Integer integer = list.get(start);
int a = dfs(target - integer, list, start + 1);
int b = dfs(target, list, start + 1);
map.put(key, a + b);
return a + b;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int target = scanner.nextInt();
int n = scanner.nextInt();
List<Integer> list = new ArrayList<>();
boolean flag = false;
for (int i = 0; i < n; i++) {
int e = scanner.nextInt();
list.add(e);
if (target >= e) {
flag = true;
}
}
if (!flag) {
System.out.println(-1);
continue;
}
int res = getNum(target, n, list);
System.out.println(res);
}
}
private static int getNum(int target, int n, List<Integer> list) {
int res = dfs(target, list, 0);
return res;
}
static Map<Pair<Integer, Integer>, Integer> map = new HashMap<>();
static int dfs(int target, List<Integer> list, int start) {
Pair<Integer, Integer> key = new Pair<>(target, start);
if (map.containsKey(key)) {
return map.get(key);
}
if (target == 0) {
map.put(key, 1
);
return 1;
}
if (start >= list.size()) {
return 0;
}
Integer integer = list.get(start);
int a = 0;
if (target >= integer) {
a = dfs(target - integer, list, start + 1);
}
int b = dfs(target, list, start + 1);
map.put(key, a + b);
return a + b;
}