前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode46. 全排列

LeetCode46. 全排列

作者头像
mathor
发布2018-07-24 15:27:35
3720
发布2018-07-24 15:27:35
举报
文章被收录于专栏:mathormathor
image
image

 标准dfs问题,只不过这道题有点麻烦在于返回的是一个List嵌套List  声明一些变量,首先是ans保存最终结果,其次是path[],存储当前选取的元素的下标,然后是boolean v[],保存元素中某个下标的值是否用过,默认值是false,用过就置为true  dfs函数中首先进行边界条件判断,如果到了边界,就将所有保存在path中的下标对应的nums[]的值赋给一个List,然后return。其次i从0到nums.length枚举每一个下标,先进行判断,没有选过才选,将i的值给到path[idx],然后将当前的v[i]置为ture,在进行下一层的dfs(idx + 1,nums),最后是回溯,将v[i]变为false

class Solution {
    public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
    public static int[] path = new int[100];
    public static boolean[] v = new boolean[100];
    public static void dfs(int idx,int[] nums) {
        if(idx >= nums.length) {
            List<Integer> tmp = new ArrayList<Integer>();
            for(int i = 0;i < nums.length;i++)
                tmp.add(nums[path[i]]);
            ans.add(tmp);
            return;
        }
        for(int i = 0;i < nums.length;i++) {
            if(!v[i]) {
                path[idx] = i;
                v[i] = true;
                dfs(idx + 1,nums);
                v[i] = false;
            }
        }
    }
    public List<List<Integer>> permute(int[] nums) {
        ans.clear();
        dfs(0,nums);
        return ans;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-07-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档