#29373: JAVA AC dfs 詳細解釋附程式碼


wer12369qaz15963@gmail.com (dentr)

學校 : 新北市立清水高中
編號 : 174903
來源 : [111.248.152.60]
最後登入時間 :
2022-07-26 15:13:49
a981. 求和問題 | From: [219.84.98.239] | 發表日期 : 2022-02-19 19:41

這題我原本用Arraylist 結果腦子好混亂 所以改用Arrays

 

思路:

1. 首先 先將 他給的那些要排的n個數字 進行排序 畢竟要由小到大

 

2.  搞一個dfs 函式 會遞迴兩種情況 一個是將 數字加上去的情況(優先執行) 一個是 數字沒有加的情況(其次)

  例: 5 10 15 <<這個組合 當處理5的時候 會分支 一個是有把10加上 跟沒加上10

 

3. 給他結束條件 第一種結束條件: 目前加上的和已經超過 m(需要的和)因此判斷這個路線是錯的 return

                      第二種結束條件: 當陣列的每個數字處理過一遍後 和=m的就是答案即貼上

 

 

 

 

 

 

 

(建議自己打過一遍,這題邏輯不難,純粹熟練度而已)

code: 

answer 是靜態變量 預設是false 每當有一次遞迴 貼出答案 代表有解

a = 目前處理的數字,在陣列中得索引

b = (代表加上去情況的和) 例  b= 5 + 10 = 15 

c = (代表沒加上去的情況) 5 不加10 so c=5  


import java.util.Scanner;

public class a981 {
static boolean answer = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNextInt()){
answer = false;
int n = input.nextInt();
int m = input.nextInt();
input.nextLine();
int[] question = new int[n];
for (int i=0;i<n;i++){
question[i] = input.nextInt();
}
for (int i =0;i<question.length;i++){
for (int e=1;e<question.length-i;e++){
if (question[e-1]>question[e]){
int t = question[e];
question[e] = question[e-1];
question[e-1]= t;
}
}
}
result(question,0,0,"",m);
System.out.print( (answer) ? "":"-1\n" );
}
}
public static void result (int[] question,int a,int b,String ans,int m){
if (a<=question.length){
if (b==m){
System.out.println(ans.substring(0,ans.length()-1));
answer =true;
return;
}
}
if (b>m ||a==question.length){
return;
}
int c=b;
b+=question[a];
result (question,a+1,b,ans+question[a]+" ",m);
result (question,a+1,c,ans,m);

}
}

 

 

 
ZeroJudge Forum