1. 程式人生 > 實用技巧 >2015-03 (不懂)

2015-03 (不懂)

等式變換
輸入一個正整數X,在下面的等式左邊的數字之間新增+號或者-號,使得等式成立。
1 2 3 4 5 6 7 8 9 = X
比如:
12-34+5-67+89 = 5
1+23+4-5+6-7-8-9 = 5
請編寫程式,統計滿足輸入整數的所有整數個數。
輸入: 正整數,等式右邊的數字
輸出: 使該等式成立的個數
樣例輸入:5
樣例輸出:21

//動態規劃
//動態方程(有點難理解):當前種類=符號位加號+符號為減號+沒有符號的種類
//dp(before,des,n,ex)= dp(before - 1, before, res + des,1) + dp(before - 1, before, res - des,1) + dp(before - 1, before*pow(10, ex)+des, res,ex+1);
// before: 需要判定的符號前面的數字的個數,初始為8 // des: 需要判定的符號後面的數字,初始為9 // n:方程右邊的結果 // ex:階乘數,因為符號有三種可能,加號,減號,或者沒有,如果沒有,那麼ex就用於計算當前值 #include<iostream> #include<cmath> using namespace std; int dp(int before, int des, int res,int ex) { if (before == 0) { if (des == res) { return 1; }
else { return 0; } } else { return dp(before - 1, before, res + des,1) + dp(before - 1, before, res - des,1) + dp(before - 1, before*pow(10, ex)+des, res,ex+1); } } int main(){ int n; cin >> n; cout << dp(8,9,n,1); }