zoukankan      html  css  js  c++  java
  • 第一章课后习题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;
       }
    }
  • 相关阅读:
    面试题目-atof与ftoa
    数据结构-List
    数据结构-Vector
    面试题目-计算最大公约数
    数据结构-二分查找
    面试题目-用递归通过单字符输出打印多位的数字
    Linux-守护进程的实现
    面试题目-链表反转
    Linux-C程序的存储空间布局
    Linux-如何添加路由表
  • 原文地址:https://www.cnblogs.com/code-future/p/11419267.html
Copyright © 2011-2022 走看看