问题描述如下:
给定整数序列a1,a2,…,an,判断是否可以从中选出若干数,使它们的和恰好为k.
1≤n≤20
-108≤ai≤108
-108≤k≤108
样例:
输入
n=4
a={1,2,4,7}
k=13
输出:
Yes (13 = 2 + 4 + 7)
package LanqiaoBeautiful._7Recurtion;
import java.util.ArrayList;
import java.util.Scanner;
public class PartSum {
private static int kk;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//4
int[] a = new int[n];//1,2,4,7
for(int i=0;i<a.length;i++) {
a[i]=sc.nextInt();
}
int k = sc.nextInt();//13
kk=k;
dfs(a,k,0,new ArrayList<Integer>());
}
static void dfs(int[] a, int k, int cur,ArrayList<Integer> ints) {
if(k==0) {
System.out.print("YES ("+kk+" = ");
int size = ints.size();
for(int i=0;i<size;i++) {
System.out.print(ints.get(i) + (i == size-1?"":" + "));
}
System.out.println(")");
System.exit(0);
}
if(k<0 || cur==a.length) return;
dfs(a,k,cur+1,ints);//不要cur这个元素
ints.add(a[cur]);
int index = ints.size()-1;
dfs(a,k-a[cur],cur+1,ints);//要cur这个元素
ints.remove(index);//回溯
}
}