public class Test {
/** *//** *//** *//** *//** *//** *//** *//**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new QueenOne(new String[] { "1", "2", "3", "4" }).run(); //方法一
new QueenTwo(new String[] { "1", "2", "3", "4" }).run(); //方法二
}
}
方法一:(利用数学当中的多项式合并来解决----(a+b+c)*(a+b+c)*(a+b+c) )
package org.minli;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class QueenOne {
private String[] num;
public QueenOne() {
}
public QueenOne(String[] num) {
this.num = num;
}
public void run(String[] nums) {
List numsList = Arrays.asList(nums);
for (int i = 1; i < nums.length; i++) {
numsList = join(numsList, nums);
}
printNums(numsList);
}
public List join(List<String> dest, String[] src) {
List tempList = new ArrayList();
for (String str : src) {
for (String temp : dest) {
if (temp.indexOf(str) == -1) {
tempList.add(temp + str);
}
}
}
return tempList;
}
public void printNums(List<String> numsList) {
for (String str : numsList) {
System.out.println(str);
}
}
}
方法二:(利用常规思路) (1,2,3,4)
package org.minli;
import java.util.*;
class NewNum {
// 保存数字
private List<String> nums = new ArrayList<String>();
public NewNum() {
}
private NewNum(List nums) {
this.nums = nums;
}
/** *//**
*添加数字
*/
public NewNum addNum(String num) {
if (!checkNum(num)) {
List<String> temp = new ArrayList<String>(nums);
temp.add(num);
return new NewNum(temp);
}
return null;
}
/** *//**
*检查数字
*/
public boolean checkNum(String targetNum) {
for (String num : nums) {
if (num.equals(targetNum)) {
return true;
}
}
return false;
}
/** *//**
*格式化输出
*/
public String toString() {
StringBuilder temp = new StringBuilder();
for (String num : nums) {
temp.append(num + " ");
}
return temp.toString();
}
}
public class QueenTwo {
private String[] nums;
public QueenTwo() {
}
public QueenTwo(String[] nums) {
this.nums = nums;
}
/** *//**
*组合数字
*/
private List makeNum(List<NewNum> allNewNums, int count) {
if (count == 1)
return allNewNums;
List<NewNum> newAllNewNums = new ArrayList<NewNum>();
for (NewNum newNum : allNewNums) {
for (String num : nums) {
if (!newNum.checkNum(num)) {
NewNum temp = newNum.addNum(num);
newAllNewNums.add(temp);
}
}
}
return makeNum(newAllNewNums, count - 1);
}
/** *//**
*打印
*/
public void print(List<NewNum> allNewNums) {
for (NewNum newNum : allNewNums) {
System.out.println(newNum);
}
}
public void run() {
for (String num : nums) {
NewNum newNum = new NewNum();
List<NewNum> allNewNums = new ArrayList<NewNum>();
allNewNums.add(newNum.addNum(num));
allNewNums = makeNum(allNewNums, nums.length);
print(allNewNums);
}
}
}