[LeetCode] Combination Sum 和确定的组合数的个数

声明:原题目转载自LeetCode,解答部分为原创

Problem :

        Given a set of candidate numbers (C(without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T, return the number of C.

        The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

        For example, given candidate set [2, 3, 6, 7] and target 7
        A solution set is: 

[
  [7],
  [2, 2, 3]
]

        So the result should be 2.

Solution :

         思路:第二类背包问题的又一种形式,与上篇不同的是,本题目虽然同样允许同一个数值在数组中多次出现,但不再考虑数值放入的排列顺序。在前篇的代码上稍作修改,可得如下代码:

#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> count_of_sum(target + 1, 0);
        count_of_sum[0] = 1;
        for(int i = 0; i < nums.size() ; i ++)
        {
        	int add = nums[i];
        	for(int j = 0 ; j <= target - add; j ++)
        	{
        		count_of_sum[j + add] += count_of_sum[j];
			}
			
			for(int k = 0 ; k <= target ; k ++)
			{
				cout << count_of_sum[k] << " ";
			}
			cout << endl;
		}
		return count_of_sum[target];
    }
};

int main()
{
	Solution text;
	vector<int> temp(4,0);
	temp[0] = 2;
	temp[1] = 3;
	temp[2] = 6;
	temp[3] = 7;
	cout << text.combinationSum4(temp, 7) << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值