题目简介:
给定的数组,给定的k,数组中的是否可以选出若干个数字之和为k
数组:nums
数量为n
目标和为k
代码如下:
public class PartSum {
static int n;
static int k;
static int[] nums;
public static void input(){
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = in.nextInt();
}
}
public static void main(String[] args) {
input();
System.out.println("dfs(0,0) = " + dfs(0, 0));
}
public static boolean dfs(int i,int sum) {
if (i == n){
return sum == k;
}
if (dfs(i+1,sum)){
return true;
}
if (dfs(i+1,sum+nums[i])){
return true;
}
return false;
}
}