所有算法都基于力扣。
1.爬楼梯
public class ClimbStairs {
public static void main(String[] args) {
//输出结果
System.out.println(ClimbStairs(8));
}
public static int ClimbStairs(int n) {
//当n=1时只有一种方法爬楼梯,返回1
if (n == 1){
return 1;
}
//当n=2时有两种方法爬楼梯,返回2
if (n == 2){
return 2;
}
//将这个问题转化成为“斐波那契数列”问题进行解决
int a=1,b=2,temp;
for (int i = 3; i<= n; i++){
temp = a;
a = b;
b= temp+b;
}
return b;
}
}
2.杨辉三角(一)
输出整个杨辉三角。
public class YanghuiTriangle1 {
public static void main(String[] args) {
//显示结果
System.out.println(generate(5));
}
public static List<List<Integer>> generate(int numRows) {
//定义一个存【int类型数据的列表】类型数据的列表
List<List<Integer>> res = new ArrayList<>();
for(int i=0; i<numRows; ++i){
//定义一个int类型数据的列表
List<Integer> one = new ArrayList<>();
for(int j=0; j<=i; ++j){
//第一列和最后一列的值永远为1
if(j == 0 || j == i){
one.add(1);
//其余的为他肩上的两数之和
}else{
one.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
}
}
//将int类型数据的列表添加到存【int类型数据的列表】类型数据的列表中
res.add(one);
}
//返回存【int类型数据的列表】类型数据的列表
return res;
}
}
3.杨辉三角(二)
输出杨辉三角最后一行。
public class YanghuiTriangle2 {
public static void main(String[] args) {
//显示结果
System.out.println(getRow(5));
}
public static List<Integer> getRow(int rowIndex) {
//定义列表
List<Integer> res = new ArrayList<>(rowIndex+1);
for(int i=0; i<=rowIndex; i++){
//在第一列加上1
res.add(1);
//该行的第二个元素开始遍历,把值返回它的正上方元素与左上方元素之和。
for(int j = i-1; j>0;j--){
res.set(j,res.get(j) + res.get(j-1));
}
}
//返回结果res
return res;
}
4.斐波那契
public class Fibonacci {
public static void main(String[] args) {
//显示结果
System.out.println(fib(4));
}
public static int fib(int n) {
int a = 0, b = 1, temp;
for (int i = 0; i < n; i++) {
temp = a + b;
a = b;
b = temp;
}
return a;
}
}
5.比特位计数
public class BitCount {
public static void main(String[] args) {
countBits(5);
}
public static int[] countBits(int n) {
//建立数组
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) {
//一个数的比特位1的个数先让他等于他一半的比特位量
bits[i] = bits[i / 2];
//如果是奇数还要加1
if ((i & 1) == 1)
bits[i]++;
}
return bits;
}
}
由于对动态规划不了解,剩余两题下周不上。结束。