在爬楼梯的基础上,改为一次可以爬1阶、2阶、...一直到m阶,问一共有多少种办法爬到楼顶?
思路:这是一个完全背包问题,因为爬完一阶后,还可以再爬一阶,可以重复取;
动规五部曲
1、dp数组下标及其含义:背包容量为j的背包一共有dp[j]种办法装满;
2、递推关系式:背包装满的问题、dp[j]+=dp[j-nums[i]];
3、初始化:dp[0]=1,其余为0;
4、遍历顺序:归根到底还是排序问题,不同的顺序可以视为不同的方法,先背包后物品,背包为正序。
5、举例验证dp数组。
1、getline使用方法:getline(<字符数组chs>,<读取字符的个数n>,<终止符>)
2、stoi:string to int
3、find_if用法:按功能查找元素
- find_if( iterator beg, iterator end, _pred)
- 按值查找元素,找到的话返回指定位置的迭代器,找不到则返回结束迭代器位置
- beg :开始迭代器
- end :结束迭代器
- _pred :函数或者谓词 (返回bool类型的仿函数)
例子:
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
void test1()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>::iterator pos = find_if(v.begin(), v.end(), GreaterFive());
if (pos == v.end())
{
cout << "未找到!" << endl;
}
else
{
cout << "找到>5的数字:" << *pos << endl;
}
}
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
//初始化
vector<int> dp(target + 1, 0);
dp[0] = 1;
//遍历顺序 由于要求为排列结果,所以先背包、后物品
for (int j = 0; j <= target; j++)
{
for (int i = 0; i < nums.size(); i++)
{
if (j >= nums[i] && dp[j] < INT_MAX - dp[j - nums[i]]) dp[j] += dp[j - nums[i]];
}
}
return dp[target];
}
};
void trimLeftTrailingSpaces(string& input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string& input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
vector<int> stringToIntegerVector(string input) {
vector<int> output;
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
stringstream ss(input);
ss.str(input);
string item;
char delim = ',';
while (getline(ss, item, delim)) {
output.push_back(stoi(item));
}
return output;
}
int stringToInteger(string input) {
return stoi(input);
}
int main() {
string line;
while (getline(cin, line)) {
vector<int> nums = stringToIntegerVector(line);
getline(cin, line);
int target = stringToInteger(line);
int ret = Solution().combinationSum4(nums, target);
string out = to_string(ret);
cout << out << endl;
}
return 0;
}