zl程序教程

您现在的位置是:首页 >  其他

当前栏目

04-05组合问题_算法训练

训练算法 组合 04 05 问题
2023-09-11 14:21:00 时间

算法训练

匪警请拨110,即使手机欠费也可拨通!

为了保障社会秩序,保护人民群众生命財产安全,警察叔叔须要与罪犯斗智斗勇,因而须要常常性地进行体力训练和智力训练。

某批警察叔叔正在进行智力训练:

1 2 3 4 5 6 7 8 9 = 110;

请看上边的算式,为了使等式成立,须要在数字间填入加号或者减号(能够不填。但不能填入其他符号)。之间没有填入符号的数字组合成一个数。比如:12+34+56+7-8+9 就是一种合格的填法;123+4+5+67-89 是还有一个可能的答案。

求请你利用计算机的优势,帮助警察叔叔高速找到全部答案。

提每一个答案占一行。形如:

12+34+56+7-8+9

123+4+5+67-89

......

// 数字间填写符号 + -
// 1 2 3 4 5 6 7 8 9 = 100;


import java.util.*;

public class MyA
{
	public static void f(String cur, int goal, List<Integer> lst)
	{	
		if(lst.size()==0) return;
		
		int a = lst.remove(lst.size()-1);
		if(lst.size()==0)
		{
			if(goal==a) System.out.println(a + cur);
			return;
		}
	
		List<Integer> lst2 = new Vector<Integer>();
		lst2.addAll(lst);
		List<Integer> lst3 = new Vector<Integer>();
		lst3.addAll(lst);
				
		f("+" + a + "" + cur, goal-a, lst2);
		f("-" + a + "" + cur, goal+a, lst3);
		
		int b = lst.remove(lst.size()-1);
		lst.add(Integer.parseInt(b+""+a));
		f(cur, goal, lst);
	} 
	
	public static void main(String[] args)
	{
		List<Integer> lst = new Vector<Integer>();
		for(int i=1; i<=9; i++) lst.add(i);
		
		f("", 110, lst);
	}
}

版权声明:本文博主原创文章,博客,未经同意不得转载。