標籤:ext span security auto div ice list a演算法 cal
題目
/*You are a professional robber planning to rob houses along a street. * Each house has a certain amount of money stashed, * the only constraint stopping you from robbing each of them is that * adjacent houses have security system connected and * it will automatically contact the police if two adjacent houses were broken into on the same night. * Given a list of non-negative integers representing the amount of money of each house, * determine the maximum amount of money you can rob tonight without alerting the police. * *//*你是一個職業搶劫犯,打算沿著街道搶劫房子。 * 每個房子都有一定量的存款,唯一的約束阻止你搶它們是相鄰的房屋有安全系統串連, * 它會自動與警方聯絡,如果兩個相鄰的房屋被分解成在同一個晚上。 * 給出一個代表每個房子的錢的非負整數的列表,確定今晚你能搶劫的最大金額而不必警示。 * */
代碼
動態規劃法(重點)
1 //動態規劃 2 import java.util.*; 3 public class Main { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 int a = sc.nextInt(); 7 int aa[] = new int[a]; 8 for(int i=0;i<aa.length;i++){ 9 aa[i] = sc.nextInt();10 }11 if(aa.length==1){12 System.out.println(aa[0]);13 return;14 }15 if(aa.length==2){16 System.out.println(Math.max(aa[0],aa[1]));17 return;18 }19 aa[2] += aa[0];20 if(aa.length==3){21 System.out.println(Math.max(aa[2], aa[3]));22 return;23 }24 for(int i=3;i<aa.length;i++){25 aa[i] += Math.max(aa[i-2], aa[i-3]);26 }27 System.out.println(Math.max(aa[aa.length-1], aa[aa.length-2]));28 }29 }
解析
最優解的問題一般都可以用動態規划算法
動態規划算法:
1.全域最優解中一定包含某個局部最優解,但不一定包含前一個局部最優解,因此需要記錄之前的所有最優解
2.動態規劃的關鍵是狀態轉移方程,即如何由以求出的局部最優解來推導全域最優解
3.邊界條件:即最簡單的,可以直接得出的局部最優解
狀態轉移方程: aa[i] += Math.max(aa[i-2], aa[i-3]); (i>=4)
因為相鄰的兩個不能一起計算,所以最後還要比較最後一個和倒數第二個的大小以求出最優解
【JAVA演算法題】職業搶劫