From f8855e6597b78f6b71d4d19d0637d984664c1d94 Mon Sep 17 00:00:00 2001 From: Chen Xu Date: Wed, 24 Aug 2022 21:43:19 -0400 Subject: [PATCH] Day 9 - DFS --- DFS.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/DFS.java b/DFS.java index 8e7101e..62a90bc 100644 --- a/DFS.java +++ b/DFS.java @@ -99,4 +99,35 @@ private void combinations(int target, int index, int[] coins, List cur, } } + /** + * All Permutations I + *

+ * Given a string with no duplicate characters, return a list with all + * permutations of the characters. + */ + public List permutations(String input) { + List result = new ArrayList<>(); + char[] ch = input.toCharArray(); + permutations(ch, 0, result); + return result; + } + + private void permutations(char[] ch, int index, List result) { + if (index == ch.length) { + result.add(String.valueOf(ch)); + return; + } + + for (int i = index; i < ch.length; i++) { + swap(ch, index, i); + permutations(ch, index + 1, result); + swap(ch, index, i); + } + } + + private void swap(char[] ch, int a, int b) { + char temp = ch[a]; + ch[a] = ch[b]; + ch[b] = temp; + } }