中级农民
- 积分
- 107
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-3-10
- 最后登录
- 1970-1-1
|
[quote]害群之蚂蚁 发表于 2019-5-14 05:30
- public class Coin_Word_Backtracking {
- public boolean find(String[] coins ...[/quote]
- 嗯,我也感觉第二轮用backtrack毕竟靠谱。下面是我写的,大概看了一下,似乎思路差不多?
- [code] public boolean formLetter(char[][] list, String word) {
- // for every char character from A to Z, create a Set to store all the indices of coins where a char exists in the list
- ArrayList<Set<Integer>> coinsForletter = new ArrayList<>();
- for (int i = 0; i < 26; i++) {
- coinsForletter.add(i, new HashSet<>());
- }
- for (int i = 0; i < list.length; i++) {
- coinsForletter.get(list[i][0] - 'A').add(i);
- coinsForletter.get(list[i][1] - 'A').add(i);
- }
- return backtrack(coinsForletter, word.toCharArray(), new HashSet<Integer>(), 0);
- }
-
- // visited: a set of indices of coins that have already used one side (so we cannot use the other side anymore
- private boolean backtrack(ArrayList<Set<Integer>> coinsForletter, char[] letters, Set<Integer> visited, int start) {
- if (start >= letters.length) return true;
-
- char c = letters[start];
- for (Integer coin : coinsForletter.get(c - 'A')) {
- if (!visited.contains(coin)) {
- visited.add(coin);
- // if can continue all the way to the end, then it means we can return true for index `start`
- if (backtrack(coinsForletter, letters, visited, start + 1)) return true;
- // if backtrack() returns false above, it means that path cannot go through, so we backtrack
- visited.remove(coin);
- }
- }
- return false;
- }
复制代码
补充内容 (2019-6-10 13:48):
这里假设所有字母都是大写字母。如果是任意unix code,那就换成Map<Character, Set<Integer>>就行了 |
|