暑假算法7.9,Day08
基础动态规划
第一题
class Solution {
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int p = 0, q = 0, tmp;
for (int i = 2; i <= n; i++) {
tmp = q;
q = Math.min(p + cost[i - 2], q + cost[i - 1]);
p = tmp;
}
return q;
}
}
第二题
class Solution {
public boolean canJump(int[] nums) {
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (i > k)
return false;
k = Math.max(k, i + nums[i]);
}
return true;
}
}
第三题
class Solution {
public int minSteps(int n) {
if(n <= 1){
return 0;
}
int[] dp = new int[n+1];
dp[1] = 0;
for(int i = 2;i <= n;i++){
dp[i] = 1 + (i-1);
for(int j = 1;j <i;j++){
if(i % j == 0){
dp[i] = Math.min(dp[i], dp[j] + 1 + (i-j) / j);
}
}
}
return dp[n];
}
}
第四题
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k;
while(cin>>n>>k)
{
if(k == n || k == 0)
cout<<"0 0"<<endl;
else
{
int m = n / 3;
if(k <= m)
{
cout<<"1 "<<2*k<<endl;
}
else{
cout<<"1 "<<n-k<<endl;
}
}
}
return 0;
}