Java算法学习之旅-常用算法思想

学习一门语言是相对容易的,但编写一个高质量的程序却没那么简单。

常用的算法思想有:
1.穷举算法思想
2.递推算法思想
3.递归算法思想
4.分治算法思想
5.概率算法思想

一、穷举算法(Exhaustive attack method)
列出每一种可能,找出正确的结果,依赖于计算机强大的计算能力,效率较低,同时也比较简单,具体实现就是一个个去尝试。

package com.zt.algorithm.exhaustive.attack.method;

import java.util.Scanner;

/**
 * 鸡兔同笼问题,从上面数共有35个头,从下面数共有94个脚
 * 问有多少鸡,多少兔
 * 采用穷举法,也就是一个一个去尝试
 * 
 * 这题比较简单,可以直接采用公式法
 * @author hp
 *
 */
public class ChickenRabbitDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {

        System.out.println("穷举法鸡兔同笼问题");
        Scanner scanner = new Scanner(System.in);
        int head = scanner.nextInt();
        int foot = scanner.nextInt();
        System.out.println("头的个数为:"+head);
        System.out.println("脚的个数为:"+foot);
        scanner.close();

        //int chicken = computeByQiongJu(head, foot);
        int chicken = ComputeDirectly(head, foot);

        if(chicken<0)
        {
            System.out.println("无解");
        }
        else{
            System.out.println("鸡的数量为"+chicken+",兔的数量为"+(head-chicken));
        }

    }

    public static int computeByQiongJu(int head, int foot)
    {
        int chicken=-1;
        // 鸡的数量为i,兔的数量为j
        int i,j;

        // 将鸡的个数从0开始列举,依次计算
        for(i=0;i<=head;i++)
        {
            j=head-i;
            if (2*i+4*j==foot)
            {
                chicken=i;
                break;
            }
        }
        return chicken;
    }

    private static int ComputeDirectly(int head, int foot)
    {
        int chicken=-1;
        chicken = (4*head-foot)/2;
        return chicken;
    }

}

二、递推算法
找出事物发展的规律,逐步推导,总结成公式,从而求解

package com.zt.algorithm.ditui.method;

/**
 * 题目:如果一对两个月大的兔子以后每月都可以生一对小兔子,而一对新生的兔子出生后
 * 两个月才可以生小兔子,也就是说,1月份出生,3月份才可以产仔,那么一年后有多少只兔子
 * 假设每月发生死亡事件
 * @author hp
 *
 */

public class FibonacciDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("一年后兔子总数为"+fibonacci(12));

    }

    public static int fibonacci(int n)
    {
        if (n==1||n==2)
        {
            return 1;
        }

        return fibonacci(n-1)+fibonacci(n-2);
    }

}

三、递归算法
反复调用自己,直到满足结束条件

package com.zt.algorithm.digui.method;

public class FactorialDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {

        System.out.println("12的阶乘为"+factorial(12));

    }

    public static int factorial(int n)
    {
        if (n==1)
        {
            return 1;
        }

        return n*factorial(n-1);
    }

}

四、分治算法
将一个复杂的问题化解为若干个同性质的简单问题,然后递归求解,最后合并得到最终的结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值