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

来源:互联网 发布:formal mac 编辑:程序博客网 时间:2024/05/20 18:04

声明:原题目转载自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;}


原创粉丝点击