http://ac.nbutoj.com/Problem/view.xhtml?id=1479
- 问题描述
-
There are N numbers, no repeat. All numbers is between 1 and 120, and N is no more than 60. then given a number K(1 <= K <= 100). Your task is to find out some given numbers which sum equals to K, and just tell me how many answers totally,it also means find out hwo many combinations at most.
- 输入
-
There are T test cases.
For each case:
First line there is a number N, means there are N numbers.
Second line there is a number K, means sum is K.
Third line there lists N numbers.
See range details in describe. - 输出
-
Output the number of combinations in total.
- 样例输入
-
2 5 4 1,2,3,4,5 5 6 1,2,3,4,5
- 样例输出
-
2 3
题意:给出n个数,要找出加起来等于k的方法有几种,要注意,1+2 = 3 与2+1=3,这是一样的情况思路:与杭电SUM IT UP那道题是一样的,果断DFS#include <stdio.h> #include <algorithm> #include <string.h> using namespace std; int a[1000],n,m,cnt; int cmp(int a,int b) { return a>b; } void dfs(int pos,int sum) { int i; if(sum>m) return ; if(sum == m) cnt++; for(i = pos; i<n; i++) { dfs(i+1,sum+a[i]); while(i+1<n && a[i] == a[i+1]) i++; } } int main() { int t,i; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(i = 0; i<n-1; i++) scanf("%d,",&a[i]); scanf("%d",&a[i]); sort(a,a+n,cmp); cnt = 0; dfs(0,0); printf("%d\n",cnt); } return 0; }