计算n!
def Factorial(n):
if n<=1:
return 1
return n*Factorial(n-1)
factorial(6)
6factorial(5)
6(5factorial(4))
6(5(4factorial(3)))
6(5(4(3factorial(2))))
6(5(4(3(2factorial(1)))))
6(5(4(3(21))))
6(5(4(32))
6(5(46))
6(524)
6120
720
class Solution {
public:
long long GetCni(int n, int i) {
i = (n - i > i)? i : (n - i);
if(i == 0) return 1;
else return GetCni(n, i-1)*(n-i+1)/i;
}
int climbStairs(int n) {
int i = 0;
int Sum = 0;
while(i <= n/2) {
Sum += GetCni(n-i, i);
i++;
}
return Sum;
}
};
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n==0)
return res;
if(n==1)
{
res.push_back("()");
return res;
}
string s = "";
for(int i = 0 ;i < n;++i)
s+="()";
sort(s.begin(),s.end());
do{
if(IsLegal(s))
res.push_back(s);
}while(next_permutation(s.begin()+1,s.end()));
return res;
}
bool IsLegal(string& s)
{
int count = 0;
for(int i = 0;i < s.size();++i)
{
if(s[i]=='(')
count++;
else
count--;
if(count<0)
return false;
}
return true;
}
};
原文:https://www.cnblogs.com/liugangjiayou/p/12398626.html