K好数

蓝桥杯 ALGO-3 K好数

问题描述
如果一个自然数N的K进制表示中任意的相邻的两位都不是相邻的数字,那么我们就说这个数是K好数。求L位K进制数中K好数的数目。例如K = 4,L = 2的时候,所有K好数为11、13、20、22、30、31、33 共7个。由于这个数目很大,请你输出它对1000000007取模后的值。

输入格式
输入包含两个正整数,K和L。

输出格式
输出一个整数,表示答案对1000000007取模后的值。
样例输入
4 2
样例输出
7
数据规模与约定
对于30%的数据,KL <= 106

对于50%的数据,K <= 16, L <= 10;

对于100%的数据,1 <= K,L <= 100。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int k = sc.nextInt();
		int l = sc.nextInt();
		dp(k, l);
		sc.close();
	}

	private static void dp(int k,int l){
		//数组是l行k列
		int[][] array = new int[l][k];
		for(int i=1;i<k;i++){
			array[0][i] = 1;
		}
		
		//i表示行,也就是位数
		//j表示列,也就是可能去得到的进制数
		for(int i=1;i<l;i++){
			for(int j=0;j<k;j++){
				for(int tempj=0;tempj<k;tempj++){
					if(j!=(tempj+1) && j!=(tempj-1)){
						array[i][j] = (array[i][j]+array[i-1][tempj]) % 1000000007;
					}
				}
			}
		}
		
		BigInteger sum = new BigInteger("0");
		for(int i=0;i<k;i++){
			sum = sum.add(new BigInteger(Integer.toString(array[l-1][i])));
		}
		System.out.println(sum.mod(new BigInteger("1000000007")));
	}
}

此博主配有图文讲解:https://blog.csdn.net/yztfst/article/details/86599291

原文地址:https://www.cnblogs.com/AIchangetheworld/p/12850838.html