Backpack VI

19 篇文章 0 订阅
4 篇文章 0 订阅

问题描述

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];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值