6、打印一串字母的所有排列组合

一、打印所有排列

import java.util.Arrays;

public class PaiLie {

	public static void main(String[] args) {
		String res = "abc";
		char[] ch = res.toCharArray();
		print(ch,0);
	}
	public static void print(char[] ch,int index)
	{
		if(ch==null || index<0)
		{
			System.out.println("输入错误");
			return;
		}
		if(index == ch.length-1)
			System.out.println(Arrays.toString(ch));
		else
		{
			for(int i=index;i<ch.length;i++)
			{
				swap(ch,i,index);
				
				print(ch,index+1);
				
				swap(ch,i,index);
			}
		}
	}
	public static void swap(char[] ch,int x,int y)
	{
		char temp = ch[x];
		ch[x] = ch[y];
		ch[y] = temp;
	}
}

 
6、打印一串字母的所有排列组合_第1张图片
 

二、打印所有组合

 

package day18;

public class Combination1 {   

public static void main(String[] args) {   
		String input = "abcd"; 
		int num = 4; 
		Combine(input, num);   
	}   
	private static void Combine(String input, int num) {   
		char[] a = input.toCharArray();   
		String b = "";   
		Combine(a, num, b, 0);   
	}   
	private static void Combine(char[] a, int num, String b, int low)
	{   
		if (num == 0) 
		{   
			System.out.println(b);   
		} 
		else
		{   
			for (int i = low; i < a.length; i++)
			{   
				b += a[i];   
				Combine(a, num - 1, b, i+1);   
				b=b.substring(0, b.length()-1);   
			}   
		}   
	}   
}  




 
 

你可能感兴趣的:(组合,排列)