java实现排列组合(通俗易懂)

Posted zzlback

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现排列组合(通俗易懂)相关的知识,希望对你有一定的参考价值。

 

个人感觉这篇文章(原文地址见文章尾)写的排列组合问题,非常的好,而且是一步一步引出排列组合问题,我也是看了这篇文章,一步一步按照这个思路来,最后会了自己的一套排列组合

也因此在算法竞赛中,两次用到了,成功解决了问题.

 

第一个问题:

  首先,先让我们来看第一个问题, 有1,2,3,4这4个数字.可以重复的在里面选4次,问能得到多少种结果.easy

  1  1  1  1

  1  1  1  2

  1  1  1  3  

  1  1  1  4

  1  1  2  1

  1  1  2  2

  .......

  4  4  4  3

  4  4  4  4

 

  代码实现其实也很简单,大家可以看下代码,理解一下,再自己敲一下,应该可以很快敲出来

 

import java.util.Stack;

public class Main {
	
	public static Stack<Integer> stack = new Stack<Integer>();
	public static void main(String[] args) {
		int shu[] = {1,2,3,4};
		f(shu,4,0);
	}
	/**
	 * 
	 * @param shu	待选择的数组
	 * @param targ	要选择多少个次
	 * @param cur	当前选择的是第几次
	 */
	private static void f(int[] shu, int targ, int cur) {
		// TODO Auto-generated method stub
		if(cur == targ) {
			System.out.println(stack);
			return;
		}
		
		for(int i=0;i<shu.length;i++) {
			stack.add(shu[i]);
			f(shu, targ, cur+1);
			stack.pop();
			
		}
	}

}

  输出:

[1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 1, 3]
[1, 1, 1, 4]
[1, 1, 2, 1]
[1, 1, 2, 2]
[1, 1, 2, 3]
[1, 1, 2, 4]
[1, 1, 3, 1]
[1, 1, 3, 2]
[1, 1, 3, 3]
[1, 1, 3, 4]
[1, 1, 4, 1]
[1, 1, 4, 2]
[1, 1, 4, 3]
[1, 1, 4, 4]
[1, 2, 1, 1]
[1, 2, 1, 2]
[1, 2, 1, 3]
[1, 2, 1, 4]
[1, 2, 2, 1]
[1, 2, 2, 2]
[1, 2, 2, 3]
[1, 2, 2, 4]
[1, 2, 3, 1]
[1, 2, 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3  2  4
......
4  2  1  2
4  3  2  1


 有没有发现要的到排列的情况,这里stack里的元素是1,2,3,4都不能重复

那么我在入栈的时候加个判断,如果比如1,已经在stack里面了,就不加进去,就不会得到  1   1  1  1 ...的情况了,就得到了排列

import java.util.Stack;

public class Main {
	
	public static Stack<Integer> stack = new Stack<Integer>();
	public static void main(String[] args) {
		int shu[] = {1,2,3,4};
		f(shu,4,0);
	}
	/**
	 * 
	 * @param shu	待选择的数组
	 * @param targ	要选择多少个次
	 * @param cur	当前选择的是第几次
	 */
	private static void f(int[] shu, int targ, int cur) {
		// TODO Auto-generated method stub
		if(cur == targ) {
			System.out.println(stack);
			return;
		}
		
		for(int i=0;i<shu.length;i++) {
			if(!stack.contains(shu[i])) {
				stack.add(shu[i]);
				f(shu, targ, cur+1);
				stack.pop();
			}
			
		}
	}

}

  输出:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]

  

这就是想要的排列结果了..

 

第三个问题:

明天待续....

 

 

 

原文地址:  https://blog.csdn.net/Ring_k/article/details/79575533

以上是关于java实现排列组合(通俗易懂)的主要内容,如果未能解决你的问题,请参考以下文章

ios SKU 组合算法

排列组合的数学公式

java实现冒泡排序-通俗易懂

最通俗易懂的Redis发布订阅及代码实战

组合和聚合的区别,通俗易懂。

Java链表详解--通俗易懂(超详细,含源码)