矩阵从左上角向右下角走,每次只能向右或者向下移动,求经过最小的路径
先通过动态规划求出最小路径的值,然后根据dp二维数组倒推所走路径。参考找出最大公共子序列解法。
#include<iostream> #include<vector> #include<algorithm> using namespace std; int minsum(vector<vector<int>>a, vector<int>®){ vector<vector<int>>dp(a.size(), vector<int>(a[0].size(), a[0][0])); for (int i = 1; i < a.size(); i++){ dp[i][0] = dp[i - 1][0]+a[i][0]; } for (int j = 1; j < a[0].size(); j++){ dp[0][j] = dp[0][j - 1] + a[0][j]; } for (int i = 1; i < a.size(); i++){ for (int j = 1; j < a[0].size(); j++){ dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + a[i][j]; } } /*for (int i = 0; i < dp.size(); i++){ for (int j = 0; j < dp[0].size(); j++){ cout << dp[i][j] << " "; } cout << endl; }*/ int i = dp.size() - 1; int j = dp[0].size() - 1; while (i >= 0 && j >= 0){ reg.push_back(a[i][j]); if (i > 0 && j > 0){ if (dp[i][j - 1] > dp[i - 1][j]){ i--; } else{ j--; } continue; } else if (i == 0){ j--; } else{ i--; } } return dp[a.size()-1][a[0].size()-1]; } int main(){ vector<vector<int>>a = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } }; vector<int>reg; int res = minsum(a,reg);
reverse(reg.begin(), reg.end()); for (int i = 0; i < reg.size(); i++){ cout << reg[i] << endl; } system("pause"); return 0; }