代码都是自己的代码,并不一定是这道题的最优解法,仅供参考。
小明很挑食,一共有N种食物可供挑选,他可以选其中的M种,也可以一种都不选,而且他从来不会选择连续的食物。比如,有三种食品,他可以选其中一种,也可以选2种,也可以不选。不能三种都选,因为没有隔开。
输入N,返回他有多少种挑法。
比如,
输入:
3
输出:
5
挑法可以是不挑,1,2,3,13这五种
做完这道题,主要的感受是,数学真的很重要,而且很多时候需要记得公式才能做出来。
C++解法
#include<iostream>
#include<string>
using namespace std;
int stair_multiply(int n) {
if (n == 0) return 1;
int res = 1;
while (n > 1) {
res *= n;
n--;
}
return res;
}
int pick_gap_n_m(int n, int m) {
return stair_multiply(n - m + 1) / (stair_multiply(n - 2 * m + 1)*stair_multiply(m));
}
int main() {
int n;
cin >> n;
int res = 1, num;
if (n % 2 == 0) num = n / 2;
else num = n / 2 + 1;
for (int i = 1; i < num+1 ; i++) {
res += pick_gap_n_m(n, i);
}
cout << res << endl;
system("pause");
return 0;
}
python解法
def jiecheng(x):
if x == 0:
return 1
res = 1
while (x > 1):
res *= x
x -= 1
return res
def pick_n(n, m):
return jiecheng(n - m + 1) // (jiecheng(n - 2*m+1) * jiecheng(m))
def pick(n):
res = 1
num = n // 2 if n % 2 == 0 else n // 2 + 1
for i in range(1, num+1):
res += pick_n(n, i)
return res
if __name__ == '__main__':
n = int(input())
print(pick(n))
全AC哦~