java算法(1,2,3,5,7,11,13,17,19,23,29,31)12个元素,取出4个元
发布网友
发布时间:2022-05-14 05:55
我来回答
共2个回答
热心网友
时间:2023-10-05 13:35
感觉最简单应该是4层循环,就12个元素,也不用怎么优化。
public class Test {
public static void main(String []args){
int[] arr = {1,2,3,5,7,11,13,17,19,23,29,31};
for(int i=0;i<arr.length-3;i++){
for(int j=i+1;j<arr.length-2;j++){
for(int k=j+1;k<arr.length-1;k++){
for(int h=k+1;h<arr.length;h++){
int sum = arr[i]+arr[j]+arr[k]+arr[h];
if(sum>=40 && sum <=47){
System.out.println(sum+" "+arr[i]+" "+arr[j]+" "+arr[k]+" "+arr[h]);
}
}
}
}
}
}
}
热心网友
时间:2023-10-05 13:35
// 既然你看不惯我那个方法,就给你个新的方法好了,以答治答。
import java.util.ArrayList;
import java.util.List;
public class Combination
{
public static void print(List list)
{
int sum = 0;
String str = "";
for(Object o : list)
{
String a = o.toString();
sum += Integer.parseInt(a);
str += a + " ";
}
if(sum > 39 && sum < 48){
System.out.println(str);
}
}
public static void combination(int n, int position, List choice_list, List current_choice)
{
for(int i = position; i < choice_list.size(); i++)
{
current_choice.add((Object) choice_list.get(i));
if(current_choice.size() == n)
{
print(current_choice);
}
else
{
combination(n, i + 1, choice_list, current_choice);
}
current_choice.remove(current_choice.size() - 1);
}
}
public static void main(String[] args)
{
List str_list = new ArrayList();
String str = "1,2,3,5,7,11,13,17,19,23,29,31";
String[] arr = str.split(",");
for(int i = 0; i < arr.length; i++){
str_list.add(arr[i]);
}
List current_choice = new ArrayList();
combination(4, 0, str_list, current_choice);
}
}