微软面试题_3个字母的组合

微软面试题_3个字母的组合

Contents

题目

求三个字母的组合,个数1-3都可以

解答

方法1

public class Combination {
    public static void main(String[] args) {
        char[] array = new char[]{'a', 'b', 'c'};
        List<List<Character>> res = allCombinations(array);
    }

    private static List<List<Character>> allCombinations(char[] array) {
        List<List<Character>> res = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            List<Character> tmp1 = new ArrayList<>();
            tmp1.add(array[i]);
            res.add(tmp1);
            for (int j = i + 1; j < array.length; j++) {
                List<Character> tmp2 = new ArrayList<>();
                tmp2.add(array[i]);
                tmp2.add(array[j]);
                res.add(tmp2);
                for (int k = j + 1; k < array.length; k++) {
                    List<Character> tmp3 = new ArrayList<>();
                    tmp3.add(array[i]);
                    tmp3.add(array[j]);
                    tmp3.add(array[k]);
                    res.add(tmp3);
                }
            }
        }
        return res;
    }
}

复杂度分析

时间复杂度:O(n^3)
空间复杂度:O(1)

posted @ 2021-05-08 17:05  Howfar's  阅读(105)  评论(0)    收藏  举报