zoukankan      html  css  js  c++  java
  • 整数变换问题——回溯方法

    问题描述:

    整数i的两种变换定义为向下取整

    设计一个算法求给定两个整数ab,用最少次数的变换将整数a变换为b;例如 4= gfgg(15)

    解题思路:

    使用二叉树方式表示方法g和方法f,左边节点为方法g,右边节点为方法f,利用方法调用实现循环,直至数字变换成功。

    package com.lanxi.demo1;
    import java.util.*;
    public class TransInt {
    	static int m;
    	static int tempcount,bestcount;//当前变换次数,最佳变换次数
    	static int[] temp1=new int[100];
    	static int[] temp2=new int[100];
    	public static void main(String args[]){
    		Scanner input=new Scanner(System.in);
    		System.out.println("请输入需变换的整数");
    	    int n=input.nextInt();
    	    System.out.println("请输入需变换后的整数");
    	    m=input.nextInt();
    	    tempcount=0;
    	    bestcount=100;
    	    Transform(n);
    	    System.out.println(bestcount);
    	    for(int i=bestcount;i>=1;i--){
    	    	if(temp2[i]==2)System.out.print("f");
    	        if(temp2[i]==1)System.out.print("g");
    	    }
    	}
    
    	public static void Transform(int t){
    		if(t==m){//需变换的数字成功变换
    			if(tempcount<bestcount){
    				bestcount=tempcount;//将最小转换次数赋值给bestcount
    				for(int i=1;i<=bestcount;i++){
    					temp2[i]=temp1[i];//temp2存最小次数转换方法
    					}
    				}
    			return ;
    	}
    
    	int temp=t/2;
    	tempcount++;
    	if(tempcount<bestcount&& t>0){
    		temp1[tempcount]=1;//使用方法g赋值为1
    		Transform(temp);
    	}
    	tempcount--;//回溯
    		
    	temp=3*t;
    	tempcount++;
    	if(tempcount<bestcount){
    		temp1[tempcount]=2;//使用方法f赋值为2
    		Transform(temp);
    	}
    	tempcount--;//回溯
    	}
    	}
    

      

  • 相关阅读:
    高可靠JAVA项目
    C语言JS引擎
    星际争霸,FF反作弊对战平台
    【转】ffluos编译
    〓经典文字武侠游戏 书剑 书剑江湖自由度超高!公益服!〓
    全局解释器锁GIL
    创建多线程Thread
    线程的简述Thread
    进程池的回调函数callback
    进程池的同步与异步用法Pool
  • 原文地址:https://www.cnblogs.com/www-x/p/8192904.html
Copyright © 2011-2022 走看看