Java 洛谷 P1464 Function
生活随笔
收集整理的這篇文章主要介紹了
Java 洛谷 P1464 Function
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:https://www.luogu.com.cn/problem/P1464
知識講解:
記憶化搜索實際上是遞歸來實現的,但是遞歸的過程中有許多的結果是被反復計算的,這樣會大大降低算法的執行效率。
而記憶化搜索是在遞歸的過程中,將已經計算出來的結果保存起來,當之后的計算用到的時候直接取出結果,避免重復運算,因此極大的提高了算法的效率
代碼實例:
import java.util.Scanner;
public class Main {public static final int f[][][] =new int[30][30][30];//開辟一個數組 f[][][],用來存儲計算出來的結果public static void main(String[] args) {Scanner scanner = new Scanner (System.in);boolean falg = true;int a = 0,b = 0,c = 0;//輸入數據while(falg) {a = scanner.nextInt();b = scanner.nextInt();c = scanner.nextInt();if(a==-1&&b==-1&&c==-1) {break;} else {System.out.println("w("+a+", "+b+", "+c+") = "+w(a, b, c)); }}scanner.close();}//記憶搜索(遞歸)public static int w(int a,int b,int c) {if(a<=0 || b<=0 || c<=0) {return 1;}else if(a>20 || b>20 || c>20) {return w(20,20,20);}else if(f[a][b][c]!=0) {return f[a][b][c]; //如果之前被計算過,那么直接返回存在數組中的結果;沒有計算過的,就進行的計算 }else if(a<b && b<c) {f[a][b][c] = w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c);}else {f[a][b][c] = w(a-1,b,c)+w(a-1,b-1,c)+w(a-1,b,c-1)-w(a-1,b-1,c-1);}return f[a][b][c];}}總結
以上是生活随笔為你收集整理的Java 洛谷 P1464 Function的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构-记忆化搜索讲解
- 下一篇: Android Studio——字体大小