蓝桥杯练习题 和为T(DFS)

问题描述
  从一个大小为n的整数集中选取一些元素,使得它们的和等于给定的值T。每个元素限选一次,不能一个都不选。
输入格式
  第一行一个正整数n,表示整数集内元素的个数。
  第二行n个整数,用空格隔开。
  第三行一个整数T,表示要达到的和。
输出格式
  输出有若干行,每行输出一组解,即所选取的数字,按照输入中的顺序排列。
  若有多组解,优先输出不包含第n个整数的;若都包含或都不包含,优先输出不包含第n-1个整数的,依次类推。
  最后一行输出总方案数。
样例输入
5
-7 -3 -2 5 9
0
样例输出
-3 -2 5
-7 -2 9
2
数据规模和约定
  1<=n<=22
  T<=maxlongint
  集合中任意元素的和都不超过long的范围
 
 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     
 5     static int n,count,T;
 6     static int[] a = new int[22];
 7     static int[] b = new int[22];
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         
11     Scanner sc = new Scanner(System.in);
12     n =sc.nextInt();
13     
14     for(int i =0;i<n;i++)
15     {
16         a[i]=sc.nextInt();
17     }
18     T=sc.nextInt();
19     
20     count = 0;
21     findAns(n-1,0,0);
22     System.out.println(count);
23     
24 
25     }
26     
27     static void findAns(int aIndex, int bIndex, int sum)
28     {
29         if(aIndex < 0){
30             return;
31         }
32 
33 
34         findAns(aIndex-1, bIndex, sum);
35         b[bIndex] = a[aIndex];
36         sum += a[aIndex];
37         if(sum == T){
38             count ++;
39             print(bIndex);
40         }
41         findAns(aIndex-1, bIndex+1, sum);
42     }
43     
44     static  void print(int bIndex)
45     {
46         int i;
47 
48         for(i=bIndex; i>=0; i--){
49             System.out.print(b[i]+" ");
50         }   
51         System.out.println();
52 
53     }
54     
55 }
原文地址:https://www.cnblogs.com/fjl-vxee/p/6657573.html