leetcode-64-鏈€灏忚矾寰勫拰
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-64-鏈€灏忚矾寰勫拰相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e5%ba%94%e8%af%a5' title='搴旇'>搴旇
浣跨敤 鍥犳 鏁扮粍 浜岀淮鏁扮粍 min 涓ょ 璁捐 pre棰樼洰鎻忚堪锛?/span>
缁欏畾涓€涓寘鍚潪璐熸暣鏁扮殑 m x n 缃戞牸锛岃鎵惧嚭涓€鏉′粠宸︿笂瑙掑埌鍙充笅瑙掔殑璺緞锛屼娇寰楄矾寰勪笂鐨勬暟瀛楁€诲拰涓烘渶灏忋€?/span>
璇存槑锛氭瘡娆″彧鑳藉悜涓嬫垨鑰呭悜鍙崇Щ鍔ㄤ竴姝ャ€?/span>
绀轰緥:
杈撳叆:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
杈撳嚭: 7
瑙i噴: 鍥犱负璺緞 1鈫?鈫?鈫?鈫? 鐨勬€诲拰鏈€灏忋€?/span>
瑕佸畬鎴愮殑鍑芥暟锛?/span>
int minPathSum(vector<vector<int>>& grid)
璇存槑锛?/span>
1銆佺粰瀹氫竴涓簩缁存暟缁刧rid锛岃〃绀轰竴涓綉鏍间腑鎵€鏈夌偣鐨勪唬浠凤紝瑕佹壘鍒颁竴鏉′粠缃戞牸宸︿笂瑙掑埌鍙充笅瑙掔殑璺緞锛屽彧鑳藉悜涓嬭蛋锛屾垨鑰呭悜鍙宠蛋锛屼娇寰楄繖鏉¤矾寰勪笂鐨勪唬浠风殑鍜屾渶灏忋€?/span>
鏈€鍚庤繑鍥炶繖涓渶灏忕殑浠d环鍜屻€?/span>
2銆佽繖閬撻濡傛灉浣跨敤鏆村姏绌蜂妇娉曪紝闄や簡鏈€鍚庝竴琛岀殑鍏冪礌鍜屾渶鍚庝竴鍒楃殑鍏冪礌閮藉彧鏈変竴绉嶉€夋嫨澶栵紙鍙充笅瑙掑厓绱犳病鏈夐€夋嫨锛夛紝鍏朵綑鍏冪礌閮芥湁涓ょ閫夋嫨銆?/span>
姣斿绗竴琛岀涓€鍒楃殑鍏冪礌1锛屽彲浠ラ€夋嫨寰€鍙宠蛋鎴栬€呭線涓嬭蛋锛屼袱绉嶉€夋嫨銆?/span>
褰撶綉鏍煎彉澶т箣鍚庯紝绌蜂妇娉曞お鑰楁椂浜嗐€傚洜姝ゆ垜浠噰鐢ㄥ叾浠栨柟娉曘€?/span>
瀛︿範杩囩畻娉曡璁$殑鍚屽涓€鐪嬭繖閬撻搴旇灏辫兘鎯冲埌鍔ㄦ€佽鍒掔殑鏂规硶銆?/span>
鎴戜滑鐢ㄥ姩鎬佽鍒掔殑鏂规硶璁板綍鍒拌揪姣忎竴涓偣鐨勬渶灏忚矾寰勪唬浠枫€?/span>
宸︿笂瑙掔殑鍏冪礌鐨勬渶灏忚矾寰勪唬浠疯偗瀹氬氨鏄嚜韬€?/span>
鍏朵綑鍏冪礌鐨勬渶灏忚矾寰勪唬浠凤紝瑕佷笉灏辨槸宸﹁竟鍏冪礌鐨勬渶灏忚矾寰勪唬浠?鑷韩浠d环锛岃涓嶅氨鏄笂鏂瑰厓绱犵殑鏈€灏忚矾寰勪唬浠?鑷韩浠d环锛屾渶鍚庝袱鑰呬箣涓彇涓€涓皬鐨勶紝浣滀负鑷韩杩欎釜鍏冪礌鐨勬渶灏忚矾寰勪唬浠枫€?/span>
涓嶆柇鍦拌凯浠d笅鍘伙紝鏈€鍚庡彸涓嬭鐨勫厓绱犵殑鏈€灏忚矾寰勪唬浠峰氨鏄垜浠墍姹傜殑銆?/span>
浠g爜濡備笅锛氾紙闄勮瑙o級
int minPathSum(vector<vector<int>>& grid) { if(grid.empty())return 0;//濡傛灉鐭╅樀鏄┖鐨勶紝閭d箞杩斿洖0
int hang=grid.size(),lie=grid[0].size(); vector<vector<int>>record(hang,vector<int>(lie,0));//鍒濆鍖栦竴涓煩闃电敤鏉ヨ褰曟瘡涓€涓偣鐨勬渶灏忚矾寰勪唬浠?/span>
for(int i=0;i<hang;i++) { for(int j=0;j<lie;j++) { if(i==0&j==0)//濡傛灉鏄乏涓婅鐨勫厓绱狅紝浠d环绛変簬鑷韩 record[i][j]=grid[i][j]; else { if(i==0)//濡傛灉鏄0琛岀殑鍏冪礌锛屼唬浠峰彧鑳戒粠宸﹁竟鍏冪礌鈥滅户鎵库€濊繃鏉? record[i][j]=record[i][j-1]+grid[i][j]; else if(j==0)//濡傛灉鏄0鍒楃殑鍏冪礌锛屼唬浠峰彧鑳戒粠涓婃柟鍏冪礌鈥滅户鎵库€濊繃鏉? record[i][j]=record[i-1][j]+grid[i][j]; else//濡傛灉鏄腑闂撮儴鍒嗙殑鍏冪礌锛屽氨鍙栦袱鑰呬箣涓皬鐨勯偅涓€涓? record[i][j]=min(record[i][j-1]+grid[i][j],record[i-1][j]+grid[i][j]); } } } return record[hang-1][lie-1]; }
涓婅堪浠g爜瀹炴祴8ms锛宐eats 96.95% of cpp submissions銆?/span>
以上是关于leetcode-64-鏈€灏忚矾寰勫拰的主要内容,如果未能解决你的问题,请参考以下文章