所以問題是創建一個函式來列印給定字串的所有排列并將它們存盤在陣列串列中。我的代碼如下:
import java.util.ArrayList;
class Solution
{
public static void permutations (String str, String perms, ArrayList<String> sets){
// base case
if(str.length() == 0){
sets.add(perms);
return;
} // end of base case
for(int i =0; i<str.length(); i ){
char currentChar = str.charAt(i);
String newStr = str.substring(0,i) str.substring(i 1);
permutations(newStr, perms currentChar, sets);
return;
}// end of for
} // end of permutations() function
public static void main(String args[]){
ArrayList<String> sets = new ArrayList<>();
permutations("ABC", "", sets);
System.out.println(sets);
}// end of main
}// end of class
我面臨的問題是 ArrayList 只存盤第一個變體;即,只有ABC,其他都沒有。我一直試圖找出錯誤很長一段時間,但找不到它。如果有人幫忙會很高興:)
PS 這是一個不使用 ArrayList 來存盤變體并直接列印它們的代碼。此代碼正常作業:
/*Q) recursive function to print all the permutations of a string*/
class Permutations{
public static void printPerms(String str, String permutation){
// base case
if(str.length()==0){
System.out.println(permutation);
return;
}// end of base case
for(int i = 0; i<str.length(); i ){
char currentChar = str.charAt(i);
String newStr = str.substring(0,i) str.substring(i 1);
printPerms(newStr, permutation currentChar);
} // end of for
} // end of printPerms
public static void main(String args[]){
String str = "abc";
printPerms(str, "");
} // end of main()
}// end of class
uj5u.com熱心網友回復:
return僅當當前迭代中的所有字符都已被訪問時,才需要在基本情況下執行。
但是在您的示例中,代碼在呼叫printPerms函式后回傳,因此在為 0 處的 char 處理 1 次迭代后,它回傳并且不處理字串中的任何其他字符。
洗掉/注釋for回圈中的 return 陳述句。
for(int i =0; i<str.length(); i ){
char currentChar = str.charAt(i);
String newStr = str.substring(0,i) str.substring(i 1);
printPerms(newStr, perms currentChar, sets);
//return;
}// end of for
uj5u.com熱心網友回復:
我找到了。問題在for回圈中。您的代碼包含return回圈結束時的陳述句。當我洗掉它時,代碼正在運行。
for(int i =0; i<str.length(); i ){
char currentChar = str.charAt(i);
String newStr = str.substring(0,i) str.substring(i 1);
permutations(newStr, perms currentChar, sets);
return; // issue is in this line
}
順便提一句。我的 IDE 向我顯示Dead code警告i 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/486350.html
