我正在尝试解决一个问题,我必须找到 3 个数字,对于 t 种情况,它们加起来等于数字 n。
这是限制
Given four numbers N,A,B,C, find three numbers that sum up to N, with the following restrictions:
The first number must be an integer between 0 and A (inclusive)
The second number must be an integer between 0 and B (inclusive)
The third number must be an integer between 0 and C (inclusive)
我目前有一个可行的解决方案,但是我的解决方案打印出每个可能的答案,而不仅仅是第一个正确答案。一旦找到第一个解决方案,我如何才能返回到第一个 for 循环?
这里是问题的链接:https://dmoj.ca/problem/ac19p1
这是我的代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int t = input.nextInt();
for(int i=0;i<t;i++){
int n = input.nextInt();
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
if(n<0){
System.out.println("-1");
}
else{
for(int one=0; one<(a+1); one++){
for(int two=0; two<(b+1); two++){
for(int three=0; three<(c+1); three++){
if((one+two+three)==n){
System.out.println(one+" "+two+" "+three);
break;
}
}
}
}
}
}
}
}
输入:
1
100
100
53
49
正确的解决方案:
0 51 49
我当前的解决方案:
0 51 49
0 52 48
0 53 47
1 50 49
1 51 48
1 52 47
1 53 46
2 49 49
2 50 48
...
最佳答案
使用标签。
endItAll:
for(int one=0; one<(a+1); one++){
for(int two=0; two<(b+1); two++){
for(int three=0; three<(c+1); three++){
if((one+two+three)==n){
System.out.println(one+" "+two+" "+three);
break endItAll;
}
}
}
}
教程中的更多信息:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
关于java - 如何从嵌套的 for 循环中断到其最外层循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61197414/