数据结构与算法分析的课后习题编写带有下列声明的例程:public void permute( String str );private void permute( char [] str, int low, int high );第一个例程是驱动程序,它调用第二个例程并显示String str中的字符的所有排列。如果str是"abc",那么输出的串则是abc,acb,bac,bca,cab和cba。第二个例程使用递归。答案如下:public class Permute{public void permute ( String str ){ permute (str.toCharArray (), 0, str.length ()); String tmp = new StringBuilder ().append (str).reverse ().toString (); permute (tmp.toCharArray (), 0, tmp.length ());}private void permute ( char[] str, int low, int high ){ if (low == high) { return; } String result = ""; for ( int i = low; i < high; i++ ) { result += str[i]; } if (result.length () < str.length) { int count = str.length - result.length (); for ( int i = 0; i < count; i++ ) { result += str[i]; } } System.out.println (result); permute (str, ++low, high);}public static void main ( String[] args ){ Permute permute = new Permute (); permute.permute ("abc");}}上面的代码,虽然也是方法自己调用自身,但感觉permute (str, ++low, high);这样的调用其实用for循环就能写出来,这个应该不能算是递归吧,求更好的递归解法
添加回答
举报
0/150
提交
取消