问题描述
http://www.lintcode.com/zh-cn/problem/backpack-vi/
Given an integer array nums with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
注意事项
The different sequences are counted as different combinations.
样例
Given nums = [1, 2, 4], target = 4
The possible combination ways are:
[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]
[2, 2]
[4]
return 6
笔记
在规模较小的时候使用回溯法可以输出所有可能的结果,如代码1所示,但是规模变大就不行了,还是要用动态规划。
动态规划:如代码2所示。
假设buff[i]的意思是,容量为i的时候,有多少种装的方法。
每次考虑把当前num[j]的空间腾出来,然后装进去num[j]。这样的话需要考虑buff[i-num[j]]有多少种方法,把这些方法加到当前的buff[i]中去。
初始化buff[0]=1,因为,假如buff[2]=0,第一件物品num[0] = 2,那么根据上面所说,buff[2]+=buff[0],现在buff[2]应该为2,因为把第一件物品2放进去空包里也算一种方法。
代码1
//
// main.cpp
// test
//
// Created by SteveWong on 8/5/16.
// Copyright © 2016 SteveWong. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
/**
* @param nums an integer array and all positive numbers, no duplicates
* @param target an integer
* @return an integer
*/
int backPackVI(vector<int>& nums, int target) {
// Write your code here
int cnt = 0;
vector<int> tmp;
getOne(nums, target, cnt, tmp);
return cnt;
}
void getOne(vector<int> &nums, int target, int &cnt, vector<int> &tmp)
{
if (target == 0)
{
cnt++;
for (auto i : tmp)
{
cout << i << ' ';
}
cout << endl;
return;
}
for (auto i : nums)
{
if (target >= i)
{
tmp.push_back(i);
getOne(nums, target-i, cnt, tmp);
tmp.pop_back();
}
}
}
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
vector<int> nums = {1,2,4};
int target = 4;
Solution sol;
sol.backPackVI(nums, target);
return 0;
}
代码2
class Solution {
public:
/**
* @param nums an integer array and all positive numbers, no duplicates
* @param target an integer
* @return an integer
*/
int backPackVI(vector<int>& nums, int target) {
// Write your code here
const int nItem = nums.size();
vector<int> buff(target+1, 0);
buff[0] = 1;
for (int i = 1; i <= target; i++)
{
for (int j = 0; j < nItem; j++)
{
if (i >= nums[j])
buff[i] += buff[i-nums[j]];
}
}
return buff[target];
}
};