第一章课后习题1.6

1.6 编写带有下列声明的例程:

public void permute(String str);

private void permute(char[] str, int low, int high);

第一个例程是个驱动程序,它调用第二个例程并显示String str中的字符的所有排列。例如,str是"abc", 那么输出的串则是abc,acb,bac,bca,cab,cba,第二个例程使用递归。

package com.algorithm.chapterone;

/**
 * 编写带有下列声明的例程:
 * public void permute(String str);
 * private void permute(char[] str, int low, int high);
 * 第一个例程是个驱动程序,它调用第二个例程并显示String str中的字符的所有排列。
 * 例如,str是"abc", 那么输出的串则是abc,acb,bac,bca,cab,cba,第二个例程使用递归。
 * @author Gao·Rongzheng
 *
 */
public class QuestionFive {
    public static int count = 0;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        permute("abcde");
        System.out.println(count);
    }
    
    public static void permute(String str) {
        char[] charArray = str.toCharArray();
        permute(charArray, 0, charArray.length);
    }
    
    private static void permute(char[] str, int low, int high) {
        if (low == high-1) {
            for (int i=0; i<high; i++) {
                System.out.print(str[i] + " ");
            }
            System.out.println();
            count++;
        } else {
            for (int i=low; i<high; i++) {
                swap(str, low, i);
                permute(str, low+1, high);
                swap(str, low, i);
            }
        }
        
    }
    
    public static void swap(char str[], int i, int j){
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
   }
}

 

posted @ 2019-08-27 16:46  从入门到入坟  阅读(706)  评论(0编辑  收藏  举报