关于从0-19中找出所有和是20的算式的解答

昨天,一个群里的网友,问了这么个问题:

从1到19共19个整数,请打印出利用这19个整数任意多个相加结果等于20的所有可能性。例如:
1+19;
1+2+17;
1+2+3+14;
1+2+3+4+10;
.
.
.
3+4+6+7;
3+5+12;
.
.
但是如同19+1和1+19是一样的,作为一个算式

 

 

我想了出来一个解决办法,但是,还没有进行算式过滤。先贴出来,供大家讨论。

 

package com.demo;

import java.util.ArrayList;
import java.util.List;
/**
 * 
 * @author Frank   email:zhufeng1981_888@hotmail.com
 * @since 1.0
 * 
 */
public class Expression {

	static int[] NUM = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
			17, 18, 19 };

	/**
	 * 
	 * @param num   the array of 0 to 19
	 * @param addend   the first add number
	 * @return list of expressions
	 */
	public static List<String> contains(int[] num, int addend) {
		StringBuilder sb = new StringBuilder(addend + "+");
		List<String> results = new ArrayList<String>();
		int temp;
		for (int i = 0; i < NUM.length; i++) {
			temp = 20 - addend;
			for (int j = i; j < NUM.length; j++) {

				if (temp - NUM[j] > 0) {
					sb.append(NUM[j] + "+");
					temp = temp - NUM[j];

				} else if (temp - NUM[j] == 0) {
					sb.append(NUM[j] + "");
					temp = temp - NUM[j];
					results.add(sb.toString());
					sb = new StringBuilder(addend + "+");

					break;
				} else {
					if (j < NUM.length)
						sb = new StringBuilder(addend + "+");
					continue;
				}
			}
		}

		return results;
	}

	public static void showNoneRepeatExpression() {

		List<String> allExpressions = new ArrayList<String>();
		for (int j = 0; j < NUM.length; j++) {
			List<String> list = Expression.contains(NUM, NUM[j]);
			allExpressions.addAll(list);
		}

		for (int i = 0; i < allExpressions.size(); i++) {
			System.out.println(allExpressions.get(i));
		}
	}

	public static List<String> filterHandler(List<String> list) {
		int n = list.size();

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {

			}
		}
		return list;

	}

	public static void main(String[] args) {
		showNoneRepeatExpression();
	}
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值