早教吧 育儿知识 作业答案 考试题库 百科 知识分享

问题用c或Java写一个算法:有5个数1,2,3,4,5列出这5个数所有可能的组合?比如说一位数字有1,2,3,4,5五种可能,两位数字有,12,13,14,15,21,22等25种可能,三位数有,123,234,345等125种可能,四位,五位同理

题目详情
问题用c或Java 写一个算法 :有5个数1,2,3,4,5 列出这5个数所有可能的组合?比如说一位数字有1,2,3,4,5五种可能,两位数字有,12,13,14,15,21,22等25种可能,三位数有,123,234,345等125种可能,四位,五位同理
▼优质解答
答案和解析
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class GetAssemble {

    public static Set set = new TreeSet();

    public static void doSet(String start, String[] sourceList, int max) {
        String[] olds = start.split("_");
        if (olds.length == max) {
            set.add(start.replaceAll("_", "").trim());
        }
        else {
            for (int s = 0; s < sourceList.length; s++) {
                if (Arrays.asList(olds).contains(sourceList[s])) {
                    continue;
                }
                else {
                    doSet(start + "_" + sourceList[s], sourceList, max);
                }
            }
        }
    }

    public static void doSet(String[] sourceList, int max) {
        for (int start = 0; start < sourceList.length; start++) {
            doSet(sourceList[start], sourceList, max);
        }

    }

    public static void print() {
        System.out.println("Total:" + set.size());
        int cols = 10;
        for (String s : set) {
            System.out.print(s + " ");
            if (cols-- == 1) {
                System.out.println();
                cols = 10;
            }
        }
        set.clear();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] haha = new String[] { "1", "2", "3", "4", "5" };
        System.out.println();
        System.out.println("  ");
        doSet(haha, 5);
        print();
    }

}