← 返回首页
Java递归实现排列组合
发表时间:2023-09-22 08:18:15
Java递归实现排列组合

Java递归实现排列组合。

package com.example.fastjsondemo.test;

import java.util.Stack;

public class InterviewDemo {

    public static Stack<String> stack = new Stack<String>();

    /**
     *
     * @param source 待选择的数组
     * @param targ  要选择多少个次
     * @param cur   当前选择的是第几次
     */
    private static void combination(String[] source, int targ, int cur) {
        // TODO Auto-generated method stub
        if(cur == targ) {
            System.out.println(stack);
            return;
        }
        for(int i=0;i<source.length;i++) {
            if(!stack.contains(source[i])) {
                stack.add(source[i]);
                combination(source, targ, cur+1);
                stack.pop();
            }
        }
    }

    public static void main(String[] args) {
        String[] source = {"a","b","c","d"};
        combination(source,4,0);
    }
}

运行结果:

[a, b, c, d]
[a, b, d, c]
[a, c, b, d]
[a, c, d, b]
[a, d, b, c]
[a, d, c, b]
[b, a, c, d]
[b, a, d, c]
[b, c, a, d]
[b, c, d, a]
[b, d, a, c]
[b, d, c, a]
[c, a, b, d]
[c, a, d, b]
[c, b, a, d]
[c, b, d, a]
[c, d, a, b]
[c, d, b, a]
[d, a, b, c]
[d, a, c, b]
[d, b, a, c]
[d, b, c, a]
[d, c, a, b]
[d, c, b, a]