輸入樣例:
7 3
輸出樣例:
666
這道題是暴力純搜,但是很難想,我這個是看的別人的代碼?
#include "bits/stdc++.h"
using namespace std;
int x[20][20];
int l, n;
int cnt = 0;
int sumx[5], sumy[5];
void dfs(int x, int y){if(x == n + 1) {cnt ++;return;}
// 其實不需要考慮列的和是否滿足l ,因為如果超出l的話 根本不會進入循環,如果列不足l的話,行也不可能在某一行沒有超出l的情況下一整行都達到l,所以兩個約束條件限制了sumy一定是合理的 for(int i = 0; i <= min(l - sumx[x], l - sumy[y]);i ++){ //控制剩下的元素的取值范圍 sumx[x] += i; //第x行的元素的和 sumy[y] += i; //第y列的元素的和 if(y < n) dfs(x, y +1);else if(y == n && sumx[x] == l) dfs(x + 1, 1);sumx[x] -= i;sumy[y] -= i;}
}
int main(){int a, b;cin>>l>>n;dfs(1, 1);cout<<cnt<<endl;
// cout<<ans<<endl;return 0;
}
?