Skip to content

Commit

Permalink
Day 9 - DFS
Browse files Browse the repository at this point in the history
  • Loading branch information
xckomorebi committed Aug 25, 2022
1 parent edb90e3 commit f8855e6
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions DFS.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,35 @@ private void combinations(int target, int index, int[] coins, List<Integer> cur,
}
}

/**
* All Permutations I
* <p>
* Given a string with no duplicate characters, return a list with all
* permutations of the characters.
*/
public List<String> permutations(String input) {
List<String> result = new ArrayList<>();
char[] ch = input.toCharArray();
permutations(ch, 0, result);
return result;
}

private void permutations(char[] ch, int index, List<String> 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;
}
}

0 comments on commit f8855e6

Please sign in to comment.