当前位置: 代码迷 >> J2SE >> 两个数组穷举其可能组合解决思路
  详细解决方案

两个数组穷举其可能组合解决思路

热度:64   发布时间:2016-04-24 02:14:58.0
两个数组穷举其可能组合
比如a(1,3) b(-2,-4)
新组合2个数组的元素都包括:(1,-2)(1,-2,-4)(3,-2)(3,-4)(3,-2,-4)(1,3,-2,-4);
新的组合中的元素以sring类型保存在数组中,如string a ="1,-2";

求数组a 长度为a.length ,b b.length 的所有可能组合。

------解决方案--------------------
Java code
public class TwoArrAssemble {    static void combination(int[][] array, int alength, int blength, int sub) {        if (sub >= array[0].length) {            int a = 0, b = 0;            for (int j = 0; j < array[0].length; ++j) {                if (j < alength)                    a += array[1][j];                else                    b += array[1][j];            }            if (a != 0 && b != 0) {                for (int j = 0; j < array[0].length; ++j)                    if (array[1][j] == 1)                        System.out.print(array[0][j] + "  ");                System.out.println();            }            return;        }        array[1][sub++] = 1;        combination(array, alength, blength, sub);        array[1][sub - 1] = 0;        combination(array, alength, blength, sub);    }    public static void main(String[] args) {        int[] a = { 1, 3};        int[] b = { -2, -4};        int[][] array = new int[2][a.length + b.length];        for (int i = 0; i < array[0].length; ++i) {            if (i < a.length)                array[0][i] = a[i];            else                array[0][i] = b[i - a.length];            array[1][i] = 1;        }        combination(array, a.length, b.length, 0);    }}1  3  -2  -4  1  3  -2  1  3  -4  1  -2  -4  1  -2  1  -4  3  -2  -4  3  -2  3  -4
------解决方案--------------------
以从一个数组里所有组合的代码修改一下

import java.util.Vector;

//在N个数组里分别在每个数组里选出至少一个元素组成新的数组
public class SelectNumbers
{
//在source数组里从startIndex之后(含startIndex)开始选出cout个不同的数字。结果添加进vresult向量
public void selectInArray(int [] source, Vector<String> vresult, String result, int startIndex, int cout)
{
if (cout == 1)
{
String s1 = result + "," + source[startIndex];
vresult.add(s1.substring(1));
return;
}
for (int i=startIndex+1; i<source.length; i++)
selectInArray(source, vresult, result + "," + source[startIndex], i, cout-1);
}

public void display(Vector<String> vs1, Vector<String> vs2)
{
for (int i=0; i<vs1.size(); i++)
for (int j=0; j<vs2.size(); j++)
System.out.println("(" + vs1.get(i) + ")(" + vs2.get(j) + ")");
}

public static void main(String [] args)
{
SelectNumbers demo = new SelectNumbers();
int [][] arrSource = {{1, 3}, {-2, -4}};//arrSource一维长度就是代表数组个数N
Vector<String>[] arrvs = new Vector[arrSource.length];
for (int i=0 ; i<arrSource.length; i++)
{
arrvs[i] = new Vector<String>();
for (int startIndex=0; startIndex< arrSource[i].length; startIndex++)
for (int cout=1; cout<=arrSource[i].length-startIndex; cout++)
{
String result = "";
demo.selectInArray(arrSource[i], arrvs[i], result, startIndex, cout);
}
}
demo.display(arrvs[0], arrvs[1]);
}
}
  相关解决方案