class Main {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
int n = 50;
int result = solution(n);
System.out.println(result);
System.out.println(System.currentTimeMillis());
}
public static int solution(int n) {
int result = 0;
if (n >= 1 && n <= 2){
result = n;
} else {
result = solution(n -1) + solution(n - 2);
}
return result;
}
}
class Main {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
int n = 20;
int result = solution(n);
System.out.println(result);
System.out.println(System.currentTimeMillis());
}
public static int solution(int n) {
int result = 0;
for (int oneNum = n; oneNum >= 0; oneNum--) {
if ((n - oneNum) % 2 == 0) {
result += countNum(oneNum, (n - oneNum) / 2);
}
}
return result;
}
public static int countNum(int oneNum, int twoNum) {
if (oneNum == 0 || twoNum == 0) {
return 1;
} else if (oneNum == 1 || twoNum == 1) {
return oneNum + twoNum;
}
int total = 0;
for (int i = 0; i <= oneNum; i++) {
if (oneNum - i == 0) {
total += 1;
} else {
total += countNum(oneNum - i, twoNum - 1);
}
}
return total;
}
}
在第二种写法时,递归的时候,就已经觉得是高中时学的排列组合问题了,由于一时没想起来公式是啥,就没有去实践。但结果仍然不对,那就只能去思考使用高中的排列组合公式能否可行。
排列公式:本题中不适用排列公式
组合公式:其中阶乘式比较适合使用,转化为本题,公式中n
就是走1级次数和走2级次数的总和,m
可以是1级次数或2级次数,结果相同。
class Main {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
int n = 20;
int result = solution(n);
System.out.println(result);
System.out.println(System.currentTimeMillis());
}
public static int solution(int n) {
int result = 0;
for (int oneNum = n; oneNum >= 0; oneNum--) {
if ((n - oneNum) % 2 == 0) {
result += countNum(oneNum, (n - oneNum) / 2);
}
}
return result;
}
public static int countNum(int oneNum, int twoNum) {
if (oneNum == 0 || twoNum == 0) {
return 1;
} else if (oneNum == 1 || twoNum == 1) {
return oneNum + twoNum;
}
int total = 0;
int top = 1;
for (int i = oneNum + twoNum; i > 1; i--) {
top *= i;
}
int down = 1;
for (int i = oneNum; i > 1; i--) {
down *= i;
}
for (int i = twoNum; i > 1; i--) {
down *= i;
}
total = top / down;
return total;
}
}
class Main {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
int n = 20;
int result = solution(n);
System.out.println(result);
System.out.println(System.currentTimeMillis());
}
public static int solution(int n) {
int result = 0;
for (int oneNum = n; oneNum >= 0; oneNum--) {
if ((n - oneNum) % 2 == 0) {
result += countNum(oneNum, (n - oneNum) / 2);
}
}
return result;
}
public static int countNum(int oneNum, int twoNum) {
if (oneNum == 0 || twoNum == 0) {
return 1;
} else if (oneNum == 1 || twoNum == 1) {
return oneNum + twoNum;
}
int total = 0;
int topMin = 1;
int downMax = 1;
if (oneNum > twoNum) {
topMin = oneNum;
downMax = twoNum;
} else {
topMin = twoNum;
downMax = oneNum;
}
int top = 1;
for (int i = oneNum + twoNum; i > topMin; i--) {
top *= i;
}
int down = 1;
for (int i = downMax; i > 1; i--) {
down *= i;
}
total = top / down;
return total;
}
}