LeetCode力扣之46_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]

]

package leetCode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lxw, liwei4939@126.com on 2018/3/8.
 */

/*

 为了生成所有的排列组合,当我们在递归调用栈时,需要删除最
 近添加的元素,在for循环的第一次迭代过程中,添加了以nums[0]
 开头所有的排列;此后当建立以nums[1]开头的排列时需要清除tmplist,
 它包含了for循环的第一次迭代的排列
 */
public class L046_Permutation {

    public List<List<Integer>> permute(int[] nums){
        List<List<Integer>> list = new ArrayList<>();
        backTrack(list, new ArrayList<>(), nums);
        return list;
    }

    private void backTrack(List<List<Integer>> list, List<Integer> tmpList,int[] nums){
        if (tmpList.size() == nums.length){
            list.add(new ArrayList<>(tmpList));
        } else {
            for (int i= 0; i < nums.length; i++){
                if (tmpList.contains(nums[i])){
                    continue;
                }
                tmpList.add(nums[i]);
                backTrack(list, tmpList, nums);
                tmpList.remove(tmpList.size() - 1);
            }
        }
    }

    public static void main(String[] args){
        L046_Permutation tmp = new L046_Permutation();
        int[] arr = new int[]{1, 2, 3};
        List<List<Integer>> res = tmp.permute(arr);
        System.out.println(res);
    }
}
关于回溯法,参考https://leetcode.com/problems/permutations/discuss/18239/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partioning)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值