leetcode第17题

简介: 假如是 "23" ,那么第 1 次 for 循环结束后变为 a, b, c;第 2 次 for 循环的第 1 次 while 循环 a 出队,分别加上 d e f 然后入队,就变成 b c ad ae af第 2 次 for 循环的第 2 次 while 循环 b 出队,分别加上 d e f 然后入队,就变成 c ad ae af bd be bf第 2 次 for 循环的第 3 次 while 循环 c 出队,分别加上 d e f 然后入队,就变成 ad ae af bd be bf cd ce cf这样的话队列的元素长度再也没有等于 1 的了就出了 while 循环。

image.png

top17

给一串数字,每个数可以代表数字键下的几个字母,返回这些数字下的字母的所有组成可能。

解法一 定义相乘

自己想了用迭代,用递归,都理不清楚,灵机一动,想出了这个算法。

把字符串 "23" 看成 ["a","b",c] * ["d","e","f"] ,而相乘就用两个 for 循环实现即可,看代码应该就明白了。

publicList<String>letterCombinations(Stringdigits) {
List<String>ans=newArrayList<String>();
for (inti=0; i<digits.length(); i++) {
ans=mul(ans, getList(digits.charAt(i) -'0'));
    }
returnans;
}
publicList<String>getList(intdigit) {
StringdigitLetter[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
List<String>ans=newArrayList<String>();
for (inti=0; i<digitLetter[digit].length(); i++) {
ans.add(digitLetter[digit].charAt(i) +"");
        }
returnans;
    }
//定义成两个 List 相乘publicList<String>mul(List<String>l1, List<String>l2) {
if (l1.size() !=0&&l2.size() ==0) {
returnl1;
    }
if (l1.size() ==0&&l2.size() !=0) {
returnl2;
    }
List<String>ans=newArrayList<String>();
for (inti=0; i<l1.size(); i++)
for (intj=0; j<l2.size(); j++) {
ans.add(l1.get(i) +l2.get(j));
        }
returnans;
}

解法二 队列迭代

参考这里,果然有人用迭代写了出来。主要用到了队列。


publicList<String>letterCombinations(Stringdigits) {
LinkedList<String>ans=newLinkedList<String>();
if(digits.isEmpty()) returnans;
String[] mapping=newString[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
ans.add("");
for(inti=0; i<digits.length();i++){
intx=Character.getNumericValue(digits.charAt(i));
while(ans.peek().length()==i){ //查看队首元素Stringt=ans.remove(); //队首元素出队for(chars : mapping[x].toCharArray())
ans.add(t+s);
            }
        }
returnans;
    }

假如是 "23" ,那么

第 1 次 for 循环结束后变为 a, b, c;

第 2 次 for 循环的第 1 次 while 循环 a 出队,分别加上 d e f 然后入队,就变成 b c ad ae af

第 2 次 for 循环的第 2 次 while 循环 b 出队,分别加上 d e f 然后入队,就变成 c ad ae af bd be bf

第 2 次 for 循环的第 3 次 while 循环 c 出队,分别加上 d e f 然后入队,就变成 ad ae af bd be bf cd ce cf

这样的话队列的元素长度再也没有等于 1 的了就出了 while 循环。


这种题的时间复杂度和空间复杂度自己理的不太清楚就没有写了。

相关文章
|
5月前
leetcode-472. 连接词
leetcode-472. 连接词
48 0
|
5月前
leetcode-1219:黄金矿工
leetcode-1219:黄金矿工
75 0
|
5月前
|
消息中间件 Kubernetes NoSQL
LeetCode 1359、1360
LeetCode 1359、1360
单链表反转 LeetCode 206
单链表反转 LeetCode 206
73 0
顺手牵羊(LeetCode844.)
好多同学说这是双指针法,但是我认为叫它顺手牵羊法更合适
72 0
leetcode 283 移动零
leetcode 283 移动零
55 0
LeetCode 283. 移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
84 0
|
C++ Python
LeetCode 771. Jewels and Stones
LeetCode 771. Jewels and Stones
77 0
leetcode第46题
这是自己开始想到的一个方法,考虑的思路是,先考虑小问题怎么解决,然后再利用小问题去解决大问题。没错,就是递归的思路。比如说, 如果只有 1 个数字 [ 1 ],那么很简单,直接返回 [ [ 1 ] ] 就 OK 了。 如果加了 1 个数字 2, [ 1 2 ] 该怎么办呢?我们只需要在上边的情况里,在 1 的空隙,也就是左边右边插入 2 就够了。变成 [ [ 2 1 ], [ 1 2 ] ]。
leetcode第46题