递归程序最难写......

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。 
 
代码如下,java依旧:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class Solution {
    HashSet<String> arrangeSet = new HashSet<>();
	
	
	public void DfsStr(char str[],char sequence[],int step,int strLen,boolean moveFlag[])
	{
		if(step == strLen)
		{
			String arrange = new String(sequence);
			arrangeSet.add(arrange);
			return;
		}
		
		for(int i = 0; i < strLen; i++)
		{
			if(moveFlag[i] == false)
			{
				sequence[step] = str[i];
				moveFlag[i] = true;
				DfsStr(str, sequence, step + 1, strLen, moveFlag);
				moveFlag[i] = false; //回退一步
			}
		}
		
	}
	
	public ArrayList<String> Permutation(String str) 
	{
			
	       char sequence[] = new char[str.length()];
	       boolean moveFlag[] = new boolean[str.length()];
	       char strArrary[] = str.toCharArray();
	       ArrayList<String> stringList = new ArrayList<>();
	       
	       if(str == null || str.isEmpty())
	       {
	    	   return stringList;
	       }
	       
	       for(int i = 0; i < str.length(); i++)
	       {
	    	   moveFlag[i] = false;
	       }
	       
	       DfsStr(strArrary, sequence, 0, str.length(), moveFlag);
	       
	       
	       stringList.addAll(arrangeSet);
	       Collections.sort(stringList);
	       
	       return stringList;
    }
}

  

posted @ 2015-11-14 15:41  代码的搬运工  阅读(465)  评论(0编辑  收藏  举报