当前位置:网站首页>圆环回原点问题-字节跳动高频题
圆环回原点问题-字节跳动高频题
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
圆环上有10个点,编号为0~9。从0点出发,每次可以逆时针和顺时针走一步,问走n步回到0点共有多少种走法。
示例 1:
输入: 2
输出: 2
解释:有2种方案。分别是0->1->0和0->9->0
二、解题
动态规划
这题类似于爬楼梯,使用动态规划:走n步到0的方案数=走n-1步到1的方案数+走n-1步到9的方案数。
dp[i][j]表示从0点出发走i步到j点的方案数。
状态转移方程:
- 走i步走到j的有n中方法 等于 {走i-1步到 j-1} + {走 i-1步到j+1},因为有回环,所以需要走到j-1可能为负数
- dp[i][j] = dp[i-1][(j-1+length)%length] + dp[i-1][(j+1+length)%length];
class Solution {
public int backToOrigin(int k) {
int[][] dp = new int[k + 1][10];
dp[0][0] = 1;
for (int i = 1; i <= k ; i++) {
for (int j = 0; j < 10; j++) {
dp[i][j] = dp[i - 1][(j - 1 + 10) % 10] + dp[i - 1][(j + 1) % 10];
}
}
return dp[k][0];
}
}
延伸
class Solution {
public int backToOrigin(int n, int k) {
if (n == 0) {
return 1;
}
if (n == 2) {
if (k % 2 == 0) {
return k;
} else {
return 0;
}
}
int[][] dp = new int[k + 1][n];
dp[0][0] = 1;
for (int i = 1; i < k + 1; i++) {
for (int j = 0; j < n; j++) {
dp[i][j] = dp[i - 1][(j - 1 + n) % n] + dp[i - 1][(j + 1) % n];
}
}
return dp[k][0];
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hequnwang10/article/details/124332502
边栏推荐
- JVM class loading mechanism
- [C#] 彻底搞明白深拷贝
- Manually implement call, apply and bind functions
- ASP. Net core configuration options (Part 2)
- matlab如何绘制已知公式的曲线图,Excel怎么绘制函数曲线图像?
- RPC核心概念理解
- Header built-in object
- 开期货,开户云安全还是相信期货公司的软件?
- [ES6] promise related (event loop, macro / micro task, promise, await / await)
- 基于51单片机红外无线通讯仿真
猜你喜欢
ASP. NET CORE3. 1. Solution to login failure after identity registers users
PC电脑使用无线网卡连接上手机热点,为什么不能上网
Advantages and disadvantages of several note taking software
SiteServer CMS5. 0 Usage Summary
Net standard
双闭环直流调速系统matlab/simulink仿真
为什么有些人说单片机简单,我学起来这么吃力?
. net type transfer
Why do some people say SCM is simple and I have to learn it so hard?
Using quartz under. Net core -- general properties and priority of triggers for [5] jobs and triggers
随机推荐
Using quartz under. Net core - [1] quick start
为什么有些人说单片机简单,我学起来这么吃力?
古代埃及希腊,数学用的什么进制
Preliminary understanding of promse
Promise (I)
1217_使用SCons生成目标文件
Using quartz under. Net core -- general properties and priority of triggers for [5] jobs and triggers
JVM类加载机制
Promise (II)
Exercise: even sum, threshold segmentation and difference (two basic questions of list object)
双指针进阶--leetcode题目--盛最多水的容器
1-1 NodeJS
[markdown notes]
In ancient Egypt and Greece, what base system was used in mathematics
C语言程序设计之函数的构造
Using quartz under. Net core -- operation transfer parameters of [3] operation and trigger
基于51单片机红外无线通讯仿真
Come out after a thousand calls
PC电脑使用无线网卡连接上手机热点,为什么不能上网
【WPF绑定3】 ListView基础绑定和数据模板绑定