Digital and number for the sum of
1. Title Description
Given a positive integer n and an integer array A sum, seeking selected portion of the digital array A and the sum of the number of programs. When the two selected program has a number of index is not the same, we considered different composition program.
Input Description:
Enter two rows:
a first conduct two positive integers n (1 ≤ n ≤ 1000) , sum (1 ≤ sum ≤ 1000)
The second line n positive integers A [i] (32-bit integer) to separated by a space.
Description Output:
output required number of programs
Example 1
2. Ideas (dynamic programming)
(1) is a recursive relation: DP [I] [J] DP = [1-I] [J] + DP [I-1] [jA [I]]
DP [1-I] [J]: indicates no the i-th digit can conspire where j is the most
dp [i-1] [j -value [i]]: when used i, the original conspire j-value [i] in the case where a maximum
(2) adding two DP [i] [j] Representative conspire numbers j i prior to use most, what kinds of programs.
Where i indicates an array subscript, j, and expressed as j, since the recursion relation dp [i] [j] and the i-1 only, and therefore can be optimized for space complexity O (n), i.e., dp [j] = dp when the number of ways are combined into jA [i] when the number of ways [j] + dp [jA [ i]], represents a combination as j is equal to take the current number of children a [i] plus not get to the current digital a [i] the total number of ways.
(3) dp [0] = 1; // initialize, 0 always represents one species conspire embodiment (not take any number).
3. Code
#include <iostream>
#include <vector>
using namespace std;
int main(){
int n = 0, sum = 0;
cin >> n >> sum;
vector<int> nums(n);
vector<long> dp(sum+1);
for(int i = 0;i < n;++i){
cin >> nums[i];
}
dp[0] = 1;//组合成0有一种方法,即取0个数
for(int i = 0;i < n;++i){
for(int j = sum;j >= nums[i];--j){
dp[j] += dp[j-nums[i]];
}
}
cout << dp[sum] << endl;
return 0;
}
4. Complexity Analysis
Time complexity: O (n ^ 2)
space complexity: O (n)