Permutation Sequence

来源:互联网 发布:刷手怎么找淘宝商家 编辑:程序博客网 时间:2024/05/29 15:26

此题,我不要求用最好的数学解法,现在只求最基本的,能bug free!!!!!!!

public static String getPermutation(int n, int k) {        int[] array = new int[n];        for (int i = 0; i < n; i++) {            array[i] = i + 1;        }        List<List<Integer>> result = new LinkedList<>();        List<Integer> list = new LinkedList<>();                getPermutationHelper(array, list, result, k, n);        List<Integer> tempList = result.get(result.size() - 1);            StringBuilder sb = new StringBuilder();            for (int i: tempList) {                sb.append(i);            }            String finalStr = sb.toString();        return finalStr;    }        private static void getPermutationHelper(int[] array, List<Integer> list, List<List<Integer>> result, int k, int n) {        if (result.size() < k && list.size() == n) {            result.add(new LinkedList<>(list));            return;        } else if (result.size() == k) {            return;        }        for (int i = 0; i < array.length; i++) {            if (list.contains(array[i])) {                continue;            }            list.add(array[i]);            getPermutationHelper(array, list, result, k, n);            list.remove(list.size() - 1);        }    }


0 0
原创粉丝点击