hdu1258
給你兩個數t,n
接下來輸入n個數字
讓你輸出所有數字相加等于n的組合
4 6 4 3 2 2 1 1
t n
4
3+1
2+2
2+1+1
Sample Input
4 6 4 3 2 2 1 1 5 3 2 1 1 400 12 50 50 50 50 50 50 25 25 25 25 25 25 0 0Sample Output
Sums of 4: 4 3+1 2+2 2+1+1 Sums of 5: NONE Sums of 400: 50+50+50+50+50+50+25+25+25+25 50+50+50+50+50+25+25+25+25+25+25 其實就是個簡單的dfs,一開始我還以為什么背包問題,結果發現想太多; #include <iostream> using namespace std; int n,m; int a[15],lu[15]; int cnt = 0; void dfs(int k,int t); bool flag; int main() {int i,j;while(scanf("%d%d",&m,&n) && m){flag = false;for(i=0;i<n;++i)scanf("%d",a+i);printf("Sums of %d:\n",m);dfs(-1,m);if(!flag)printf("NONE\n");} } void dfs(int k,int t) {if(t == 0){flag = true;printf("%d",lu[0]);for(int i=1; i<cnt; ++i){printf("+%d",lu[i]);}printf("\n");return ;}if(t < 0)return ;for(int j=k+1; j<n; ++j){if(t >= a[j]){lu[cnt++] = a[j];dfs(j,t-a[j]);while(j < n-1 && a[j] == a[j+1]) //防止重復的元素進入j ++;cnt --;}} }?
轉載于:https://www.cnblogs.com/mltang/p/8728446.html
總結
- 上一篇: laravel中及其常用的一些函数方法(
- 下一篇: linux安装redis并在后台启动