题目出处点这里
思路见代码:
package reintroduction_recursion;
import java. util. ArrayList;
import java. util. Scanner;
public class P1036 {
static int n;
static int k;
static ArrayList< Integer> list;
static int res = 0 ;
static boolean [ ] isUsed;
public static void main ( String[ ] args) {
Scanner sc = new Scanner ( System. in) ;
n = sc. nextInt ( ) ;
k = sc. nextInt ( ) ;
list = new ArrayList < Integer> ( ) ;
isUsed = new boolean [ n] ;
int arr[ ] = new int [ n] ;
for ( int i = 0 ; i < n; i++ ) {
arr[ i] = sc. nextInt ( ) ;
}
dfs ( arr, 0 , 0 ) ;
System. out. println ( res) ;
}
public static void dfs ( int [ ] arr, int has, int now) {
if ( has == k) {
if ( isPrime ( SUM ( ) ) ) {
res++ ;
}
return ;
}
for ( int i = now; i < n; i++ ) {
if ( ! isUsed[ i] ) {
list. add ( arr[ i] ) ;
isUsed[ i] = true ;
dfs ( arr, has+ 1 , i) ;
list. remove ( list. size ( ) - 1 ) ;
isUsed[ i] = false ;
}
}
}
public static boolean isPrime ( int sum) {
for ( int i = 2 ; i <= Math. sqrt ( sum) ; i++ ) {
if ( sum % i == 0 ) {
return false ;
}
}
return true ;
}
public static int SUM ( ) {
int sum = 0 ;
for ( int i = 0 ; i < list. size ( ) ; i++ ) {
sum = sum + list. get ( i) ;
}
return sum;
}
}