zoukankan      html  css  js  c++  java
  • 台哥算法练习 寻找和为某值的子集

    这是09年日全食那段时间,有一次班级群里,一个同学提出来的问题,当时随手写了这个算法。

    题目:从一个数字的集合里,找出所有的子集,这些子集的和等于15

    直接贴出代码咯:

    package suanfa;
    
    /**
     * 集合中寻找和为某值的子集
     * 
     * @author 台哥编程课堂
     * https://blog.csdn.net/chaohi
     * 
     * 这里是定义了个数组集合,从中查找和为15的集合。递归法和贪心法的结合,不断迭代。。
     */
    public class Jihe {
    	int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    	int target = 15;
    
    	/**
    	 * 
    	 * @param index
    	 * @param he
    	 * @param array
    	 * @param tai
    	 */
    	public void action(int index, int he, int[] array, String str) {
    		String xyz = "";
    		
    		for (int i = index; i < array.length; i++) {
    			int j = array[i];
    			xyz = str + " + " + j;
    			if (j < he) {
    				action(i + 1, he - j, array, xyz);
    			}
    			if (j == he) {
    				System.out.println(xyz.substring(3) + " =" + this.target);
    				str = "";
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		Jihe jihe = new Jihe();
    		jihe.action(0, jihe.target, jihe.array, "");
    	}
    }
    

    运行,打印结果如下:

    1 + 2 + 3 + 4 + 5 =15
    1 + 2 + 3 + 9 =15
    1 + 2 + 4 + 8 =15
    1 + 2 + 5 + 7 =15
    1 + 3 + 4 + 7 =15
    1 + 3 + 5 + 6 =15
    1 + 5 + 9 =15
    1 + 6 + 8 =15
    2 + 3 + 4 + 6 =15
    2 + 4 + 9 =15
    2 + 5 + 8 =15
    2 + 6 + 7 =15
    3 + 4 + 8 =15
    3 + 5 + 7 =15
    4 + 5 + 6 =15
    6 + 9 =15
    7 + 8 =15
     

  • 相关阅读:
    数据挖掘实践(23):实战-- 建筑能源得分预测报告(一)
    返回闭包
    函数指针
    Rust 中的 Closure
    Moves, copies and clones in Rust
    Rust的闭包类型(Fn, FnMut, FnOne的区别)
    Clone VS Copy
    rust socket
    A simple UNIX socket listener in Rust
    【firecracker】系统启动与epoll事件循环
  • 原文地址:https://www.cnblogs.com/chaohi/p/10698002.html
Copyright © 2011-2022 走看看