一、题目描述
二、代码思路
属于DP的一种(状态转换),原始dp做法转换成了递归做法,但是本质上还是状态转换,跟那个斐波那契非常类似。
或者简单方法直接 / 2 也可以。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
// dp[i]:代表有i个瓶子可以换多少瓶水
// int j = i / 3 + i % 3 : 代表换一次之后剩下的瓶子数量 int count = i / 3 表示这一轮换了多少水
// dp[i] = dp[j] + count;
// 初始值: dp[0] = 0; dp[1] = 0; dp[2] = 1; dp[3] = 1; dp[4] = 2; dp[5] = dp[1 + 2] + 1 = 2
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int cupCount = in.nextInt();
if (cupCount == 0) {
return;
}
int dp[] = new int[cupCount];
//dp[0] = 0; dp[1] = 0; dp[2] = 1; dp[3] = 1;
System.out.println(findValue(dp, cupCount));
}
}
private static int findValue(int dp[], int i) {
if (i == 3 || i == 2) {
return 1;
}
if (i == 0 || i == 1) {
return 0;
}
int count = i / 3;
int j = count + i % 3;
return findValue(dp, j) + count;
}
}