1-9,总共9个数字,不能重复,然后前一位数除以1,前两位数除以2,前三位数除以3,以此类推,前9位数除以9,都可以除尽

本文介绍了一个有趣的数学问题:寻找1到9数字的排列方式,使得从第一位开始的每n位数字组成的整数能被n整除。通过回溯算法高效解决了这一问题,并展示了完整的Java实现代码。
package structure;

import java.util.concurrent.TimeUnit;

/**
 * 1-9,总共9个数字,不能重复,然后前一位数除以1,前两位数除以2,前三位数除以3,以此类推,前9位数除以9,
 * 
 * 利用搜索法就可以,因为约束条件较为苛刻,因此效率 很快
 */
public class Baidu {
    static int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    static int count = 0;
    static void back(int t) {
	if (t == array.length) {
	    System.out.println(count);
	    return;
	}
	for (int i = t; i < array.length; i++) {
	    swap(array, t, i);
	    count = count * 10 + array[t];
	    if (count % (t + 1) == 0) {
		back(t + 1);
	    }
	    count = (count - array[t]) / 10;
	    swap(array, t, i);
	}
    }

    static void swap(int[] array, int i, int j) {
	int t = array[i];
	array[i] = array[j];
	array[j] = t;
    }

    public static void main(String args[]) {
	long start = System.currentTimeMillis();
	back(0);
	long end = System.currentTimeMillis();
	System.out.println((end - start));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值