Day-09-動態規劃 Leetcode-70, 198, 53, 32, 120, 300, 64, 174

目錄

例一:LeetCode70

例二:LeetCode198

例三:LeetCode53

例四:LeetCode32

例五:LeetCode120

例六:LeetCode300

例七:LeetCode64

例八:LeetCode174


例一:LeetCode70

/**
 You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
 */
#include <stdio.h>
#include <vector>
class Solution {
public:
       int climbStairs(int n) {
              std::vector<int> dp(n + 3, 0);  // 創建長度爲n + 3的數組,初始化爲0
              dp[1] = 1;
              dp[2] = 2;
              for (int i = 3; i <= n; i++) {
                     dp[i] = dp[i - 1] + dp[i - 2];
              }
              return dp[n];
       }
};
int main() {
       Solution solve;
       printf("%d\n", solve.climbStairs(3));
       return 0;
}

例二:LeetCode198

/**
 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.
 */
#include <stdio.h>
#include <vector>
class Solution {
public:
       int rob(std::vector<int>& nums) {
              if (nums.size() == 0) {
                     return 0;
              }
              if (nums.size() == 1) {
                     return nums[0];
              }
              std::vector<int> dp(nums.size(), 0);
              dp[0] = nums[0];
              dp[1] = std::max(nums[0], nums[1]);
              for (int i = 2; i < nums.size(); i++) {
                     dp[i] = std::max(dp[i - 1], nums[i] + dp[i - 2]);
              }
              return dp[nums.size() - 1];
       }
};
int main() {
       Solution solve;
       std::vector<int> nums;
       nums.push_back(5);
       nums.push_back(2);
       nums.push_back(6);
       nums.push_back(3);
       nums.push_back(1);
       nums.push_back(7);
       printf("%d\n", solve.rob(nums));
       return 0;
}

例三:LeetCode53

/**
 Given an integer array nums, find the contiguous subarray
 (containing at least one number) which has the largest sum and return its sum.
 */
#include <stdio.h>
#include <vector>
class Solution {
public:
       int maxSubArray(std::vector<int>& nums) {
              std::vector<int> dp(nums.size(), 0);
              dp[0] = nums[0];
              int max_res = dp[0];
              for (int i = 1; i < nums.size(); i++) {
                     dp[i] = std::max(dp[i - 1] + nums[i], nums[i]);
                     if (dp[i] > max_res) {
                           max_res = dp[i];
                     }
              }
              return max_res;
       }
};
int main() {
       Solution solve;
       std::vector<int> nums;
       nums.push_back(-2);
       nums.push_back(1);
       nums.push_back(-3);
       nums.push_back(4);
       nums.push_back(-1);
       nums.push_back(2);
       nums.push_back(1);
       nums.push_back(-5);
       nums.push_back(4);
       printf("%d\n", solve.maxSubArray(nums));
       return 0;
}

例四:LeetCode32

/**
 You are given coins of different denominations and a total amount of money amount.
  Write a function to compute the fewest number of coins that you need to make up
  that amount. If that amount of money cannot be made up by any combination of the
  coins, return -1.
 */
#include <stdio.h>
#include <vector>
class Solution {
public:
       int coinChange(std::vector<int>& coins, int amount) {
              std::vector<int> dp;
              for (int i = 0; i <= amount; i++) {
                     dp.push_back(-1);
              }
              dp[0] = 0;
              for (int i = 1; i <= amount; i++) {
                     for (int j = 0; j < coins.size(); j++) {
                           if (i - coins[j] >= 0 && dp[i - coins[j]] != -1) {
                                  if (dp[i] == -1 || dp[i] > dp[i - coins[j]] + 1) {
                                         dp[i] = dp[i - coins[j]] + 1;
                                  }
                           }
                     }
              }
              return dp[amount];
       }
};
int main() {
       Solution solve;
       std::vector<int> coins;
       coins.push_back(1);
       coins.push_back(2);
       coins.push_back(5);
       coins.push_back(7);
       coins.push_back(10);
       for (int i = 1; i <= 14; i++) {
              printf("dp[%d] = %d\n", i, solve.coinChange(coins, i));
       }
       return 0;
}

例五:LeetCode120

/**
 Given a triangle, find the minimum path sum from top to bottom.
  Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
 */
#include <stdio.h>
#include <vector>
class Solution {
public:
       int minimumTotal(std::vector<std::vector<int>>& triangle) {
              if (triangle.size() == 0) {
                     return 0;
              }
              std::vector<std::vector<int>> dp;
              for (int i = 0; i < triangle.size(); i++) {
                     dp.push_back(std::vector<int>());
                     for (int j = 0; j < triangle[i].size(); j++) {
                           dp[i].push_back(0);
                     }
              }
              for (int i = 0; i < dp.size(); i++) {
                     dp[dp.size() - 1][i] = triangle[dp.size() - 1][i];
              }
              for (int i = dp.size() - 2; i >= 0; i--) {
                     for (int j = 0; j < dp[i].size(); j++) {
                           dp[i][j] = std::min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle[i][j];
                     }
              }
              return dp[0][0];
       }
};
int main() {
       std::vector<std::vector<int>> triangle;
       int test[][10] = { {2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3} };
       for (int i = 0; i < 4; i++) {
              triangle.push_back(std::vector<int>());
              for (int j = 0; j < i + 1; j++) {
                     triangle[i].push_back(test[i][j]);
              }
       }
       Solution solve;
       printf("%d\n", solve.minimumTotal(triangle));
       return 0;
}

例六:LeetCode300

class Solution {
public:
       int lengthOfLIS(std::vector<int>& nums) {
              if (nums.size() == 0) {
                     return 0;
              }
              std::vector<int> dp(nums.size(), 0);
              dp[0] = 1;
              int LIS = 1;
              for (int i = 1; i < dp.size(); i++) {
                     dp[i] = 1;
                     for (int j = 0; j < i; j++) {
                           if (nums[i] > nums[j] && dp[i] < dp[j] + 1) {
                                  dp[i] = dp[j] + 1;
                           }
                     }
                     if (LIS < dp[i]) {
                           LIS = dp[i];
                     }
              }
              return LIS;
       }
};

/**
 Given an unsorted array of integers, find the length of longest increasing subsequence.
 */
#include <stdio.h>
#include <vector>
 // // O(n^2)
 // class Solution{
 // public:
 //    int lengthOfLIS(std::vector<int> &nums){
 //           if(nums.size() == 0){
 //                  return 0;
 //           }
 //           std::vector<int> dp(nums.size(), 0);
 //           dp[0] = 1;
 //           int LIS = 1;
 //           for(int i = 1; i < dp.size(); i++){
 //                  dp[i]  = 1;
 //                  for(int j = 0; j < i; j++){
 //                         if(nums[i] > nums[j] && dp[i] < dp[j] + 1){
 //                               dp[i] = dp[j] + 1;
 //                         }
 //                  }
 //                  if(LIS < dp[i]){
 //                         LIS = dp[i];
 //                  }
 //           }
 //           return LIS;
 //    }
 // };
 // 更優算法 用二分法優化查找後時間複雜度爲 n*logn
class Solution {
public:
       int lengthOfLIS(std::vector<int>& nums) {
              if (nums.size() == 0) {
                     return 0;
              }
              std::vector<int> stack;
              stack.push_back(nums[0]);
              for (int i = 1; i < nums.size(); i++) {
                     if (nums[i] > stack.back()) {  // 返回stack中的最後一個元素
                           stack.push_back(nums[i]);
                     }
                     else {
                           // for(int j = 0; j < stack.size(); j++){
                           //     if(stack[j] >= nums[i]){
                           //            stack[j] = nums[i];
                           //            break;
                           int pos = binary_search(stack, nums[i]);  // logn
                           stack[pos] = nums[i];
                     }
              }
              return stack.size();
       }
private:
       int binary_search(std::vector<int> nums, int target) {
              int index = -1;
              int begin = 0;
              int end = nums.size() - 1;
              while (index == -1) {
                     int mid = (begin + end) / 2;
                     if (target == nums[mid]) {
                           index = mid;
                     }
                     else if (target < nums[mid]) {
                           if (mid == 0 || target > nums[mid - 1]) {
                                  index = mid;
                           }
                           end = mid - 1;
                     }
                     else if (target > nums[mid]) {
                           if (mid == nums.size() - 1 || target < nums[mid + 1]) {
                                  index = mid + 1;
                           }
                           begin = mid + 1;
                     }
              }
              return index;
       }
};
int main() {
       int test[] = { 1, 3, 2, 3, 1, 4 };
       std::vector<int> nums;
       for (int i = 0; i < 6; i++) {
              nums.push_back(test[i]);
       }
       Solution solve;
       printf("%d\n", solve.lengthOfLIS(nums));
       return 0;
}

例七:LeetCode64

/**
 Given a m x n grid filled with non-negative numbers,
 find a path from top left to bottom right which minimizes the sum of all numbers along its path.
 */
#include <stdio.h>
#include <vector>
class Solution {
public:
       int minPathSum(std::vector<std::vector<int>>& grid) {
              if (grid.size() == 0) {
                     return 0;
              }
              int row = grid.size();
              int column = grid[0].size();
              std::vector<std::vector<int>> dp(row, std::vector<int>(column, 0));
              dp[0][0] = grid[0][0];
              for (int i = 1; i < column; i++) {
                     dp[0][i] = dp[0][i - 1] + grid[0][i];
              }
              for (int i = 1; i < row; i++) {
                     dp[i][0] = dp[i - 1][0] + grid[i][0];
                     for (int j = 1; j < column; j++) {
                           dp[i][j] = std::min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
                     }
              }
              return dp[row - 1][column - 1];
       }
};
int main() {
       int test[][3] = { {1, 3, 1}, {1, 5, 1}, {4, 2, 1} };
       std::vector<std::vector<int>> grid;
       for (int i = 0; i < 3; i++) {
              grid.push_back(std::vector<int>());
              for (int j = 0; j < 3; j++) {
                     grid[i].push_back(test[i][j]);
              }
       }
       Solution solve;
       printf("%d\n", solve.minPathSum(grid));
       return 0;
}

例八:LeetCode174

/**
 The demons had captured the princess (P) and imprisoned her in the
 bottom-right corner of a dungeon. The dungeon consists of M x N rooms
 laid out in a 2D grid. Our valiant knight (K) was initially positioned
 in the top-left room and must fight his way through the dungeon to
 rescue the princess.
The knight has an initial health point represented by a positive integer.
If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health
(negative integers) upon entering these rooms; other rooms are either
empty (0's) or contain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight
decides to move only rightward or downward in each step.
 */
#include <stdio.h>
#include <vector>
class Solution {
public:
       int calculateMinimumHP(std::vector<std::vector<int>>& dungeon) {
              if (dungeon.size() == 0) {
                     return 0;
              }
              std::vector<std::vector<int>> dp(dungeon.size(), std::vector<int>(dungeon[0].size(), 0));
              int row = dungeon.size();
              int column = dungeon[0].size();
              dp[row - 1][column - 1] = std::max(1, 1 - dungeon[row - 1][column - 1]);
              for (int i = column - 2; i >= 0; i--) {
                     dp[row - 1][i] = std::max(1, dp[row - 1][i + 1] - dungeon[row - 1][i]);
              }
              for (int i = row - 2; i >= 0; i--) {
                     dp[i][column - 1] = std::max(1, dp[i + 1][column - 1] - dungeon[i][column - 1]);
              }
              for (int i = row - 2; i >= 0; i--) {
                     for (int j = column - 2; j >= 0; j--) {
                           int dp_min = std::min(dp[i + 1][j], dp[i][j + 1]);
                           dp[i][j] = std::max(1, dp_min - dungeon[i][j]);
                     }
              }
              return dp[0][0];
       }
};
int main() {
       int test[][3] = { {-2, -3, 3}, {-5, -10, 1}, {10, 30, -5} };
       std::vector<std::vector<int>> dungeon;
       for (int i = 0; i < 3; i++) {
              dungeon.push_back(std::vector<int>());
              for (int j = 0; j < 3; j++) {
                     dungeon[i].push_back(test[i][j]);
              }
       }
       Solution solve;
       printf("%d\n", solve.calculateMinimumHP(dungeon));
       return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章