当我看到这一题的时候,就感觉可以利用数学方法解决,只要枚举前面十几个数就就能求解;因为贪心,一直减7到14,以内就肯定直接得到解。
最后用动态规划写出来,顺便复习一下动态规划,F(n)=F(n-7)+1 if:F(n-7)有解,F(n-5)+1 if:F(n-5)有解,F(n-3)+1 if:F(n-3)有解;
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] temp = new int[]{-1, -1, -1, 1, -1, 1, 2, 1}; if(n <= 7){ System.out.println(temp[n]); }else{ int[] ints = new int[n + 1]; System.arraycopy(temp, 0, ints, 0, temp.length); for(int i = 8; i <= n; i++){ int[] res = new int[3]; res[0] = ints[i - 7] == -1 ? -1 : ints[i - 7] + 1; res[1] = ints[i - 5] == -1 ? -1 : ints[i - 5] + 1; res[2] = ints[i - 3] == -1 ? -1 : ints[i - 3] + 1; Arrays.sort(res); if(res[2] == -1){ ints[i] = -1; }else if(res[1] == -1){ ints[i] = res[2]; }else if(res[0] == -1){ ints[i] = res[1]; }else{ ints[i] = res[0]; } } System.out.println(ints[n]); } } }