gpt4 book ai didi

javascript - 尝试将java中的回溯代码转换为javascript

转载 作者:行者123 更新时间:2023-12-02 06:28:12 25 4
gpt4 key购买 nike

这是一个回溯question

我尝试转换此 answers从java到javascript

Java代码

   public class Solution {
private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

public List<String> letterCombinations(String digits) {
List<String> ret = new LinkedList<String>();
combination("", digits, 0, ret);
return ret;
}

private void combination(String prefix, String digits, int offset, List<String> ret) {
if (offset >= digits.length()) {
ret.add(prefix);
return;
}
String letters = KEYS[(digits.charAt(offset) - '0')];
for (int i = 0; i < letters.length(); i++) {
combination(prefix + letters.charAt(i), digits, offset + 1, ret);
}
}
}

正确答案:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

这是我的代码:

var letterCombinations = function(digits) {
// 0, 1 no letters
global.g_keys = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
let res = [];
// prefix, digit, index, res
bt("", digits, 0, res);
return res;
};

var bt = function(px, d, ind, res) {
// push when chance?
if(ind >= d.length) {
res.push(px);
return;
}

// e.g. 2 -> ["abc"]
// we use ind+ locally, to travel digits
let les = g_keys[ parseInt(d[ind]) ];

// loop abc, same level
// px, prefix concept
for(i=0; i<les.length; i++) {
// ind+1, next level
bt(px + les[i], d, ind+1, res);
}
}

我的回答是

input: 23
output: ["ad","ae","af"]

有什么想法吗?

最佳答案

我的原始代码:

for(i=0; i<les.length; i++) {
// ind+1, next level
bt(px + les[i], d, ind+1, res);
}

正确代码(在i前面添加let)

for(let i=0; i<les.length; i++) {
// ind+1, next level
bt(px + les[i], d, ind+1, res);
}

关于javascript - 尝试将java中的回溯代码转换为javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55773538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com