题目来自:http://218.5.5.242:9018/JudgeOnline/problem.php?id=2323
5 3
0 0 5 0 1 4 0 2 3 1 1 3 1 2 2 5
回溯
题目讲解:回溯DFS,非常好用,直接上代码:
#include <bits/stdc++.h> using namespace std; int n,m,tot = 0,a[21]; bool vis[21]; void search(int x,int t,int sum){ if (x > n && sum == m){ // 输出解 tot++; for (int i = 1;i <= n;i++){ cout << a[i]; if (i != n) cout << " "; } cout << endl; return ; } if (x > n) return ; for (int i = t;i <= m - sum;i++){ // 字典序搜索,防止重复 vis[i] = true; a[x] = i; search(x+1,i,sum+i); vis[i] = false; } } int main(){ memset(vis,false,sizeof(vis)); cin >> m >> n; search(1,0,0); cout << tot; // 输出个数 return 0; }