2017-04-10 19 views
0

本週我正在做一個Java任務,我們希望使用一個集合來遞歸地通過一個字符串回溯並找到所述字符串的所有排列,最終得到一個來自包含在字符串中的數字。這一部分是很好的。問題是我們需要設置這個整數的長度,如int z所示。一串整數的排列

例如,方法maxDigit(「12345」,3)的預期輸出將是:543. 請您指出我需要在哪些方面改進我的代碼?

乾杯。

/** 
* Returns the maximum possible integer given the string str containing digits, using 
* maximum of n digits. Each digit in str can only be used once. 
**/ 
static int maxDigit(String str, int z) { 
    Set<Integer> result = new TreeSet<>(); 

    if(str.length() == 0 || z == 0) 
     return -1; 

    permute("",str,result,z); 

    int answer = 0; 
    for(int a : result) { 
     if(a > answer) 
      answer = a; 
    } 
    return answer; 
} 

/** 
* Creates a set of permutations in result based on string str with max n digits. 
**/ 
private static void permute(String acc, String str,Set<Integer> result,int z) { 
    int n = str.length(); 
    if (n == 0) 
     result.add(Integer.parseInt(acc)); 
    else { 
     if(!(z < str.length())) { 
      for (int i = 0; i < n; i++) 
       permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n), result, z); 
     } else { 
      for (int i = 0; i < n - 1; i++) 
       permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, z), result, z); 
     } 
    } 
} 
+0

我知道這並不回答你的問題,但不會排序字符串中的數字降序,並採取第一個'Z'數字導致最大的可能數量?這是O(nlogn) –

+1

@RicoKahler它肯定會,但是這特別是被設計來測試在Java中回溯的知識,所以在這種情況下排序字符串是不可能的。 – Neuw

回答

0

這似乎工作。你的邊緣條件是問題。

private static void permute(String acc, String str,Set<Integer> result,int z) { 
    int n = str.length(); 
    if (acc.length() == z) 
     result.add(Integer.parseInt(acc)); 
    else { 
     for (int i = 0; i < n; i++) 
      permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n), result, z); 

    } 
} 

System.out.println(maxDigit("1234", 2)); 
43 
+0

謝謝尼克。不幸的是,這在另一個邊緣條件下失敗,其中z超出了字符串的大小。 – Neuw

+0

...所以修復.... –

+0

沒關係,我只是傻,忘了執行檢查,在前一種方法。 +1! – Neuw