凑平方数 第七届蓝桥杯决赛javaA组

package 第七届试题;

public class 凑平方数 {
	public static boolean[] used = new boolean[10]; // 判断0-9中用过的数字
	static long[] res = new long[10];
	public static boolean[] mark;
	public static int sum = 1;

	static boolean judge(long x) {
		mark = new boolean[10];
		if (x == 0)
			return true;
		while (x != 0) {
			if (mark[(int) (x % 10)] || used[(int) (x % 10)])
				return false;
			mark[(int) (x % 10)] = true;
			x /= 10;
		}
		return true;
	}

	// count代表已经使用的位数
	// 更新标记
	static int update(long x, int count) {
		if (x == 0) {
			used[0] = true;
			count++;
			return count;
		}
		while (x != 0) {
			used[(int) (x % 10)] = true;
			x /= 10;
			count++;
		}
		return count;
	}

	// 复原标记
	static void reupdate(long x) {
		if (x == 0) {
			used[0] = false;
			return;
		}
		while (x != 0) {
			used[(int) (x % 10)] = false;
			x /= 10;
		}
	}

	// res_count:平方数的个数
	// count:已经使用的位数
	// last:最后使用的平方数
	static void dfs(int res_count, int count, long last) {
		if (count == 10) {
			for (int i = 0; i < res_count; i++)
				System.out.print(res[i] + " ");
			System.out.println(">>>" + sum);
			sum++;
			return;
		}
		for (long i = last; i <= 100000; i++) {
			if (judge(i * i)) {
				int tmpcount = update(i * i, count);
				res[res_count] = i * i;
				dfs(res_count + 1, tmpcount, i + 1);
				reupdate(i * i);
			}
		}
	}
	public static void main(String[] args) {
		dfs(0, 0, 0);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值