669.Coin Change
給出不同面額的硬幣以及一個總金額. 寫一個方法來計算給出的總金額可以換取的最少的硬幣數量. 如果已有硬幣的任意組合均無法與總金額面額相等, 那麼返回 -1
提示:最後一步爲最優策略中使用的最後一枚硬幣,子問題爲最少硬幣拼出更小的面值27-ak。
轉移方程f[X] = min{f[X-2]+1, f[X-5]+1, f[X-7]+1}
答案:
class Solution {
public:
/**
* @param coins: a list of integer
* @param amount: a total amount of money amount
* @return: the fewest number of coins that you need to make up
*/
//dp[i] - the fewest number of coins you need to make up amount i
//dp[i] = min(dp[i-1], dp[i-2], dp[i-5])+1, 前提 i-coins[j] > 0 && dp[i-coins[j]] != -1
int coinChange(vector<int> &coins, int amount) {
// write your code here
vector<int> dp(amount+1, -1);
dp[0] = 0;
for(int i = 1; i<=amount; ++i) {
for(int j = 0; j<coins.size(); ++j) {
int v = i-coins[j];
if(v >= 0 && dp[v] != -1) {
if(dp[i] == -1 || dp[v]+1<dp[i]) {
dp[i] = dp[v]+1;
}
}
}
}
return dp[amount];
}
};
114.Unique Paths
機器人位於m x n網格的左上角。機器人只能在任何時間點向下或向右移動。機器人正試圖到達網格的右下角。有多少可能的獨特路徑?
提示:初始化邊界,方式數等於上面與左面的和。
答案:
class Solution {
public:
/**
* @param m: positive integer (1 <= m <= 100)
* @param n: positive integer (1 <= n <= 100)
* @return: An integer
*/
int uniquePaths(int m, int n) {
// write your code here
vector<vector<int>> f(m,vector<int>(n));
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++){
if(i == 0 || j == 0){
f[i][j] = 1;
}
else
{
f[i][j] = f[i-1][j] + f[i][j-1];
}
}
return f[m-1][n-1];
}
};
116.Jump Game
給出一個非負整數數組,你最初定位在數組的第一個位置。
數組中的每個元素代表你在那個位置可以跳躍的最大長度。
判斷你是否能到達數組的最後一個位置。
提示:動態規劃不如貪心,可能出現過不了的情況
動態規劃遍歷1到A.size()-1,對於每個i遍歷其前面的點,如果有一個可以到達i那麼就將其設爲true。
貪心算法遍歷1到A.size()-1,設置一個變量記錄目前遍歷到的最大值,一旦i>tmpMax就返回false,不斷更新tmpMax。
答案:
class Solution {
public:
bool canJump(vector<int> A) {
int tmpMax = 0;
int n = A.size();
for (int i = 0; i < n; i++) {
if (i > tmpMax) return false;
if (tmpMax < i + A[i])
tmpMax = i + A[i];
}
return true;
}
};