例1:
Description:
现给定一个含有n个元素的数组A,要求:从这n个数中选择一些数,这些数的和恰好为k
Input:
多组测试数据。第一行为n(1<=n<=20) 第二行为n个整数,每个数的范围为(-10^8≤A[i]≤10^8) 第三行为整数k(-10^8≤k≤10^8).
Output:
如果能够达到目的,输出”Of course,I can!”; 否则输出”Sorry,I can’t!”.
Sample Input:
4
1 2 4 7
13
4
1 2 4 7
15
Sample Output:
Of course,I can!
Sorry,I can't!
代码:
import java.util.Scanner;
public class Main {
static int y;
static int v[] = new int[20], a[] = new int[20];
static int n, k;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
n = sc.nextInt();
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
k = sc.nextInt();
y = 0;
for (int i = 0; i < n; i++)
v[i] = 0;
DFS(0, 0);
if (y == 1)
System.out.println("Of course,I can");
else
System.out.println("Sorry,I can't!");
}
}
private static int DFS(int i, int sum) {
// TODO Auto-generated method stub
if (i < n && v[i] == 0) {
v[i] = 1;
if (sum + a[i] == k) {
y = 1;
return y;
} else if (sum + a[i] < k) {
DFS(i + 1, sum);
DFS(i + 1, sum + a[i]);
} else
DFS(i + 1, sum);
v[i] = 0;
}
return y;
}
}
例2:
Description:
问题很简单,给你n个正整数,求出这n个正整数中所有任选k个相乘后的和。
Input:
输入有两行,第一行是两个整数n和k,其中1<=k<=n<=10。接下去一行就是n个正整数,保证最后结果用long即可保存。
Output:
输出只有一个正整数,为最后的和。
Sample Input:
4 2
1 2 3 4
Sample Output:
35
代码:
import java.util.Scanner;
public class Main {
static long sum;
static int v[] = new int[20], a[] = new int[20];
static int n, k;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
DFS(0, 0, 1);
System.out.println(sum);
}
private static void DFS(int i, int c, int s) {
// TODO Auto-generated method stub
if (c == k) {
sum += s;
return;
}
if (i >= n)
return;
if (v[i] == 0) {
v[i] = 1;
DFS(i + 1, c + 1, s * a[i]);
DFS(i + 1, c, s);
v[i] = 0;
}
return;
}
}