我有很多,比方說123,我想生成的所有可能的方式列表的列表拆分它:如何以所有可能的方式分割數字?
[[1,2,3], [12,3], [1, 23], [123]]
我發現了一段代碼,幾乎做到這一點:http://www.quora.com/How-do-I-take-a-string-by-the-user-and-split-it-in-all-possible-ways。
我已經修改了一點:
class breakString
{
public static List<List<Integer>> res = new ArrayList<>();
public static List<List<Integer>> breaker(String input, int start, int end, List ans)
{
if(start > end)
{
System.out.println(ans);
res.add(ans);
System.out.println("res:" + res.toString());
}
else
{
ans.add(input.charAt(start) + "");
breaker(input, start+1, end, ans);
int listSize = ans.size();
ans.remove(listSize - 1);
String lastChar = ans.get(listSize - 2).toString();
ans.remove(listSize - 2);
ans.add(lastChar + input.charAt(start) + "");
breaker(input, start+1, end,ans);
}
return res;
}
public static void main(String args[])
{
String input = "123";
List ans = new ArrayList();
ans.add(input.charAt(0) + "");
breaker(input,1, input.length() - 1, ans);
System.out.println("----------------------------------------------");
for (List<Integer> intList : res)
{
System.out.println(intList);
}
}
}
但althought它打印正確的解決方案,我不能讓它回到它的權利。 輸出是:
[1, 2, 3]
res:[[1, 2, 3]]
[1, 23]
res:[[1, 23], [1, 23]]
[12, 3]
res:[[12, 3], [12, 3], [12, 3]]
[123]
res:[[123], [123], [123], [123]]
----------------------------------------------
[123]
[123]
[123]
[123]
你能告訴我如何解決它返回:
[[1,2,3], [12,3], [1, 23], [123]]
爲什麼你需要[12, 3]兩次?你的意思是[1,23]這些代幣中的一個嗎? – Constantin
對不起,我剛剛編輯它。 – pantelis300
'ans.add(input.charAt(start)+「」);'working?你能粘貼你實際執行的代碼嗎? – Karthik