• permutations(全排列)


    Given a collection of distinct 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],
      [3,2,1]
    ]

    这题是列举所有情况,回溯。

    每次都是从头开始遍历,往集合中添加元素,但是添加过的元素就不能再添加进去了,所以每次遍历就要判断当前元素有没有被使用过。因为这里没有重复元素,用contains就可以解决。有重复元素,就要有数组。

    每次遍历数组,往list中添加元素,但是不能出现重复元素,这里用其他方法跳过比较困难,可以用list的contains方法。

    class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(nums.length<=0) return result; 
            backtracking(result,new ArrayList<Integer>(),nums);
            return result;
        }
        
        public void backtracking(List<List<Integer>> result, List<Integer> list,int[] nums){
            if(list.size()==nums.length){
                result.add(new ArrayList<Integer>(list));
                return ;
            }
            
            for(int i=0;i<nums.length;i++){
                if(list.contains(nums[i])) continue;//每次都是遍历数组中的每个元素,然后添加不一样的元素(保证不重复)
                list.add(nums[i]);
                
                backtracking(result,list,nums);
                list.remove(list.size()-1);
                
            }
        }
    }
  • 相关阅读:
    python自定义线程池
    sudo: ulimit: command not found
    HTTP长连接、短连接使用及测试
    5分钟上手:本地开发环境启动HTTPS
    Python复杂对象转JSON
    Python自定义注解
    gcc makefile
    Ubuntu 13.10 安装 ia32-lib
    vim扩展配置
    python异常类型
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8120267.html
Copyright © 2020-2023  润新知