[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;}
阅读全文
0 0
- [LeetCode] Combination Sum 和确定的组合数的个数
- 【LeetCode-面试算法经典-Java实现】【216-Combination Sum III (组合数的和)】
- [leetcode 216] Combination Sum III ------组合数的和(回溯法)
- leetcode之组合数(Combination Sum)
- LeetCode--------39. Combination Sum(组合和)
- LeetCode | Combination Sum(元素的和)
- [Java代码] [Leetcode] Combination Sum 组合数之和
- [Java代码] [Leetcode] Combination Sum 组合数之和
- Combination Sum 组合数之和
- Combination Sum IV 组合数
- 和为指定数的组合个数
- leetCode 39.Combination Sum(组合总和) 解题思路和方法
- LeetCode | Combination Sum II(元素的和---2)
- Combination Sum II 组合数之和(包含有重复的元素)
- C++组合数(combination)的实现
- Combination Sum 找出Sum符合要求的组合
- Leetcode 216 Combination Sum III 组合求和
- LeetCode 39. Combination Sum(组合求和)
- Combination Sum IV 组合数
- 关于TP框架中验证码的制作
- java中你所不知道的'=='
- POJ 1616 Harmonic Periods 笔记
- IMWeb提升营Day6 | 训练题36:两个链表的第一个公共结点
- [LeetCode] Combination Sum 和确定的组合数的个数
- POJ 1617 Crypto Columns 笔记
- java关键字valatile超详细解析
- Spring Boot 初识
- ssctf-pwn2从此入坑不在起
- [LeetCode]Burst Balloons
- POJ 1618 Decorations 笔记
- ROS_Introduction
- ROS_Install