• There is integer array like {1,2,4,5,6,1,2,4,3,5,7,2,1}. I want to find the possible combination of pair which sum is 4.


    There is integer array like {1,2,4,5,6,1,2,4,3,5,7,2,1}. I want to find the possible combination of pair which sum is 4.
    input : {1,2,4,5,6,1,2,4,3,5,7,2,1}
    output : {1,1,2}, {2,2}, {3,1}, {1,2,1}...etc which make the sum as 4

    A: 

    这是一个subset sum problem问题,该类型问题的解法见 wiki,比较复杂

    http://en.wikipedia.org/wiki/Subset_sum_problem

    code sample (passed testing) 该解法是暴力法,即递归求出所有可能的组合

    View Code
    import java.util.ArrayList;
    import java.util.Arrays;

    public class Test
    {
    public static void main(String[] args)
    {
    int[] theArray={1,2,4,5,6,1,2,4,3,5,7,2,1};
    ArrayList<ArrayList<Integer>> allpairs=getPairs(theArray,0,4);
    System.out.println(allpairs.size());
    for(ArrayList<Integer> pair:allpairs)
    {
    System.out.println(Arrays.toString(pair.toArray()));
    }

    System.out.println("Complete the testing work!");
    }

    public static ArrayList<ArrayList<Integer>> getPairs(int[] theArray, int start, int sum)
    {

    if(sum==0)
    {
    ArrayList<ArrayList<Integer>> pairs=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> pair=new ArrayList<Integer>();
    pairs.add(pair);
    return pairs;
    }

    if(start>=theArray.length)
    {
    return null;
    }

    ArrayList<ArrayList<Integer>> pairs=new ArrayList<ArrayList<Integer>>();

    //situation 1 include the start element;
    ArrayList<ArrayList<Integer>> subpairs=getPairs(theArray,start+1,sum-theArray[start]);
    if(subpairs!=null)
    {
    for(ArrayList<Integer> subpair:subpairs)
    {
    ArrayList<Integer> pair=new ArrayList<Integer>();
    if(pair!=null)
    {
    pair.add(theArray[start]);
    pair.addAll(subpair);
    pairs.add(pair);
    }
    }
    }

    //situation 2 do not include the start element;
    ArrayList<ArrayList<Integer>> otherpairs=getPairs(theArray,start+1,sum);
    if(otherpairs!=null)
    {
    for(ArrayList<Integer> otherpair:otherpairs)
    {
    pairs.add(otherpair);
    }
    }
    return pairs;
    }
    }



  • 相关阅读:
    day12_字符连接单引号转意字符
    day12_存储过程说明
    day12_PLSQL编程--存储过程---统一发布动态属性管理
    linux关闭celinux服务
    day11__表管理
    day11_分区表------子分区的母模板(11g)
    day11_分区表------子分区的母模板(10g)
    day11_分区表——分区表常用维护
    smartforms 中的currquan单位处理
    当SVN服务器端IP地址发生变化时,客户端重新定位
  • 原文地址:https://www.cnblogs.com/yayagamer/p/2313998.html
Copyright © 2020-2023  润新知