动态规划应用--“杨辉三角”最短路径 LeetCode 120
生活随笔
收集整理的這篇文章主要介紹了
动态规划应用--“杨辉三角”最短路径 LeetCode 120
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 問(wèn)題描述
- 2. DP算法代碼
- 3. LeetCode 120 三角形最小路徑和
1. 問(wèn)題描述
對(duì)“楊輝三角"進(jìn)行一些改造。每個(gè)位置的數(shù)字可以隨意填寫,經(jīng)過(guò)某個(gè)數(shù)字只能到達(dá)下面一層相鄰的兩個(gè)數(shù)字。
假設(shè)你站在第一層,往下移動(dòng),我們把移動(dòng)到最底層所經(jīng)過(guò)的所有數(shù)字之和,定義為路徑的長(zhǎng)度。請(qǐng)你編程求出從最高層移動(dòng)到最底層的最短路徑。
2. DP算法代碼
/*** @description: 改造的楊輝三角,從頂層下來(lái)的最小和* @author: michael ming* @date: 2019/7/17 23:03* @modified by: */ #include <cstring> #include <algorithm> #include <iostream>using namespace std; const int high = 5; int YHTriangle[high][high] = {{5},{7,8},{2,1,4},{4,2,6,1},{2,7,3,4,5}};void shortestPath() {int states[high][high];//存放路徑距離(存較小的) // memset(states,65535,high*high*sizeof(int));states[0][0] = YHTriangle[0][0];//第一個(gè)點(diǎn)的距離int i, j;for(i = 1; i < high; ++i)//動(dòng)態(tài)規(guī)劃{for(j = 0; j <= i; ++j){if(j == 0)//在兩邊,上一個(gè)狀態(tài)沒(méi)得選,只有一個(gè)states[i][j] = states[i-1][j]+YHTriangle[i][j];else if(j == i)//在兩邊,上一個(gè)狀態(tài)沒(méi)得選,只有一個(gè)states[i][j] = states[i-1][j-1]+YHTriangle[i][j];else//在中間,上一個(gè)狀態(tài)有兩個(gè),選路徑短的states[i][j] = min(states[i-1][j],states[i-1][j-1])+YHTriangle[i][j];}}int mins = 65535, idx;for(j = 0; j < high; ++j){if(mins > states[high-1][j]){mins = states[high-1][j];//選出最短的idx = j;//記錄最短的路徑位置}}cout << "最短的路徑是:" << mins << endl;//-----------打印路徑-----------------------cout << "從底向上走過(guò)的點(diǎn)的值是:" << endl;cout << YHTriangle[high-1][idx] << " ";for(i = high-1,j = idx; i > 0; --i){if(j == 0)cout << YHTriangle[i-1][j] << " ";else if(j == i){cout << YHTriangle[i-1][j-1] << " ";j--;}else{if(states[i-1][j-1] < states[i-1][j]){cout << YHTriangle[i-1][j-1] << " ";j--;}elsecout << YHTriangle[i-1][j] << " ";}} } int main() {shortestPath();return 0; }更改數(shù)據(jù)再測(cè)試
3. LeetCode 120 三角形最小路徑和
https://leetcode-cn.com/problems/triangle/
以下解法是O(n)空間復(fù)雜度
總結(jié)
以上是生活随笔為你收集整理的动态规划应用--“杨辉三角”最短路径 LeetCode 120的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 该改变request url_
- 下一篇: POJ 3122 分披萨(二分查找)