• LeetCode


    题目:

    Given a collection of numbers, return all possible permutations.

    For example,
    [1,2,3] have the following permutations:
    [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

    思路:见缝插针

    先有了[1],然后往它的左右插入2,就是

    [1,2],[2,1],然后往这两个集合中插入3,就是

    [3,1,2] [1,3,2] [1,2,3]

    [3,2,1] [2,3,1] [2,1,3]

    package permutation;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class Permutations {
    
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            Arrays.sort(nums);
            List<Integer> subRes = new ArrayList<Integer>();
            subRes.add(nums[0]);
            res.add(subRes);
            return permute(res, nums, 1);
        }
        
        private List<List<Integer>> permute(List<List<Integer>> res, int[] nums, int pos) {
            if (pos >= nums.length) return res;
            List<List<Integer>> newRes = new ArrayList<List<Integer>>();
            for (List<Integer> subRes : res) {
                int count = subRes.size();
                for (int i = 0; i <= count; ++i) {
                    List<Integer> newSubRes = new ArrayList<Integer>(subRes);
                    newSubRes.add(i, nums[pos]);
                    newRes.add(newSubRes);
                }
            }
            return permute(newRes, nums, pos + 1);
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Permutations p = new Permutations();
            int[] nums = { 1,1,1 };
            List<List<Integer>> res = p.permute(nums);
            for (List<Integer> l : res) {
                for (int i : l)
                    System.out.print(i + "	");
                System.out.println();
            }
        }
    
    }
  • 相关阅读:
    python,jsonpath提取json数据
    [.Net] Web API 本地化与全球化
    缺省源
    组合恒等式
    20210925衡阳八中多校联测
    codeforces赛后总结——1556D. Take a Guess
    codeforces赛后总结——1556C. Compressed Bracket Sequence
    阿里云(Ubuntu20.04)搭建wordpress全流程——附图超详细版
    Linux常用命令行操作
    阿里云服务器增加监听端口
  • 原文地址:https://www.cnblogs.com/null00/p/5075551.html
Copyright © 2020-2023  润新知