3.17阿里Java后端,电商 sku 的全排列算法

3.17阿里Java后端

字典

有英文字典:Map<Character, String[]>,示例如下:
a : [a, an]
b : [bus, bird]
c : [car, can, card]
...
z : [zone]

输入 一个a-z组成的字符串,字符串每一位表示字典的key
输出 key映射的单词组成句子的集合(单词之间空格隔开)

示例:
输入:
ab
输出:
"a bus"
"an bus"
"a bird"
"an bird"

思路

递归回溯,也是电商 sku 的全排列算法。

答案

import java.util.*;

class Solution {

    public static void main(String[] args) {


        Map<Character, String[]> map = new HashMap<>();
        String[] str1 = new String[2];
        str1[0] = "a";
        str1[1] = "an";
        map.put('a', str1);
        String[] str2 = new String[2];
        str2[0] = "bus";
        str2[1] = "bird";
        map.put('b', str2);
        String[] str3 = new String[3];
        str3[0] = "car";
        str3[1] = "can";
        str3[2] = "card";
        map.put('c', str3);


        Solution solution = new Solution();

        Scanner scanner = new Scanner(System.in);

        String next = scanner.next();

        List<List<String>> list = new ArrayList<>();

        for (char c : next.toCharArray()) {
            list.add(new ArrayList<>(Arrays.asList(map.get(c))));
        }


        for (List<String> strings : solution.test(list)) {
            System.out.println(strings);
        }


    }

    public List<List<String>> test(List<List<String>> in) {
        List<List<String>> out = new ArrayList<>();
        List<String> list = new ArrayList<>();
        dfs(in, out, list, 0);

        return out;
    }

    private void dfs(List<List<String>> in, List<List<String>> out, List<String> list, Integer index) {

        if(list.size() == in.size()) {
            out.add(new ArrayList<>(list));
            return;
        }

        List<String> items = in.get(index);

        for (int i = 0; i < items.size(); i++) {
            list.add(items.get(i));
            dfs(in, out, list, index + 1);
            list.remove(list.size() - 1);
        }
    }
}

测试

输入:abc

输出

[a, bus, car]
[a, bus, can]
[a, bus, card]
[a, bird, car]
[a, bird, can]
[a, bird, card]
[an, bus, car]
[an, bus, can]
[an, bus, card]
[an, bird, car]
[an, bird, can]
[an, bird, card]

posted @ 2022-03-21 11:56  imissinstagram  Views(331)  Comments(0Edit  收藏  举报