Java集合效率问题

 

 


凑算式

B DEF
A + --- + ------- = 10
C GHI

(如果显示有问题,可以参见【图1.jpg】)


这个算式中A~I代表1~9的数字,不同的字母代表不同的数字。

比如:
6+8/3+952/714 就是一种解法,
5+3/1+972/486 是另一种解法。

这个算式一共有多少种解法?

注意:你提交应该是个整数,不要填写任何多余的内容或说明性文字。

  显然可以用暴力算法,但是需要排除元素的重复问题,刚开始我用的是Java内置的Set集合,运行时间特别长

 

package lanqiao2016;

import java.util.concurrent.ConcurrentSkipListSet;

public class T3_array {
	public static void main(String[] args) {
		int a = 0;
		int b = 0;
		int c = 0;
		int d = 0;
		int e = 0;
		int f = 0;
		int g = 0;
		int h = 0;
		int i = 0;
		int count = 0;
		
		ConcurrentSkipListSet<Integer> intSet = new ConcurrentSkipListSet<Integer>();
		
		for(a=1; a<=9; a++)
		{
			if(a > 10)
				continue;
			for(b=1; b<=9; b++)
			{
				for(c=1; c<=9; c++)
				{
					if(a + b/c > 10)
						continue;
					for(d=1; d<=9; d++)
					{
						for(e=1; e<=9; e++)
						{
							for(f=1; f<=9; f++)
							{
								for(g=1; g<=9; g++)
								{
									for(h=1; h<=9; h++)
									{
										for(i=1; i<=9; i++)
										{
											intSet.clear();
											intSet.add(a);
											intSet.add(b);
											intSet.add(c);
											intSet.add(d);
											intSet.add(e);
											intSet.add(f);
											intSet.add(g);
											intSet.add(h);
											intSet.add(i);
											if(a + (double)b/c + (double)(d*100+e*10+f)/(double)(g*100+h*10+i) == 10 
													&& intSet.size() == 9)
											{
												count++;
											}
												
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
		System.out.println(count);
	}
}

  

  后来改成直接的逻辑判断,几乎瞬间得出结果

package lanqiao2016;

public class T3 {
	public static void main(String[] args) {
		int a = 0;
		int b = 0;
		int c = 0;
		int d = 0;
		int e = 0;
		int f = 0;
		int g = 0;
		int h = 0;
		int i = 0;
		int count = 0;
		
		
		for(a=1; a<=9; a++)
		{
			if(a > 10)
				continue;
			for(b=1; b<=9; b++)
			{
				for(c=1; c<=9; c++)
				{
					if(a + b/c > 10)
						continue;
					for(d=1; d<=9; d++)
					{
						for(e=1; e<=9; e++)
						{
							for(f=1; f<=9; f++)
							{
								for(g=1; g<=9; g++)
								{
									for(h=1; h<=9; h++)
									{
										for(i=1; i<=9; i++)
										{
											if(
												a==b || a==c || a==d || a==e || a==f || a==g || a==h || a==i ||
												b==c || b==d || b==e || b==f || b==g || b==h || b==i ||
												c==d || c==e || c==f || c==g || c==h || c==i ||
												d==e || d==f || d==g || d==h || d==i ||
												e==f || e==g || e==h || e==i ||
												f==g || f==h || f==i ||
												g==h || g==i ||
												h==i 
												)
												continue;
											
											if(a + (double)b/c + (double)(d*100+e*10+f)/(double)(g*100+h*10+i) == 10)
											{
												count++;
											}
												
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
		System.out.println(count);
	}
}

  

posted @ 2019-03-19 21:20  l_____py  阅读(373)  评论(0编辑  收藏  举报