46. Permutations && 47. Permutations II && 31. Next Permutation && 60. Permutation Sequence &...

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], and [3,2,1].

Solution 1: Back-tracking
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ret = new LinkedList<List<Integer>>();
        if(nums == null)
            return ret;
        permute(nums, ret, new ArrayList<Integer>());
        return ret;
    }
    
    private void permute(int[] nums, List<List<Integer>> ret, List<Integer> current)
    {
        if(current.size() == nums.length)
        {
            List<Integer> currentCopy = new ArrayList<Integer>(current.size());
            for(Integer i : current)
                currentCopy.add(i);
            ret.add(currentCopy);
            return;
        }
        
        for(Integer num: nums)
        {
            if(current.contains(num))
                continue;
            current.add(num);
            permute(nums, ret, current);
            current.remove(num);
        }
    }
}

Solution 2: Iterative solution

public class Solution {
    public List<List<Integer>> permute(int[] num) {
        LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
        res.add(new ArrayList<Integer>());
        for (int n : num) {
            int size = res.size();
            for (; size > 0; size--) { //only process the original size.
                List<Integer> r = res.pollFirst();
                for (int i = 0; i < r.size()+1; i++) {
                    List<Integer> t = new ArrayList<Integer>(r);
                    t.add(i, n);
                    res.add(t);
                }
            }
        }
        return res;
    }
    
    //1,2,3
    //{}
    //{1}
    //{2,1}, {1,2}
    //{3,2,1}, {2,3,1}, {2,1,3}, {3,1,2}, {1,3,2}, {1,2,3}
}

 

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
        if(nums.length == 0)
            return res;         
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        permuteUnique(new LinkedList<Integer>(), res, nums, used);        
        return res;
    }
    
    public void permuteUnique(LinkedList<Integer> currentList, LinkedList<List<Integer>> res, int[] nums, boolean[] used) {
        if(currentList.size()==nums.length){
            res.add(new ArrayList<Integer>(currentList));
            return;
        }      
        Integer lastUsed = null;
        for(int i = 0; i<nums.length; ++i)
        {
            Integer current = nums[i];
            if(used[i] || current.equals(lastUsed))
                continue;          
            used[i] = true;
            lastUsed = current;
            currentList.add(lastUsed);
            permuteUnique(currentList, res, nums, used);
currentList.removeLast(); used[i]
= false; } } }

 

31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

  Array

public class Solution {
    public void nextPermutation(int[] nums) {
        int len = nums.length;
        if(len == 1)
            return;
        if(nums[len-1] > nums[len-2]) { // if  [len-2] < [len-1], swap to get next permutation.
            swap(nums, len-1, len-2);
            return;
        }
        //Here, we know [len-2] > [len-1].
        //We need to find, from right to left, the first number (named as D) that drops.
        //Once we have D, find the smallest number at D's right side, that is larger than D.
        //Swap these two numbers.
        //Then sort/flip d's right side.
        int d = len - 3;
        while(d >=0 && nums[d] >= nums[d+1]) --d; //Find the D
        
        int start = d+1;
        if(d>-1)
            for(int i = len-1; i>=d+1; --i)
                if(nums[i] > nums[d]) //Find the first number larger then D.
                {
                    swap(nums, i, d);
                    break;
                }
        //Sort the numbers at d's right.
        int mid = start + (len-start)/2;
        for(int i = start; i<mid; ++i)
            swap(nums, i, start+len-1-i);
        return;
    }
    
    private void swap(int[] array, int m, int n) {
        int temp = array[m];
        array[m] = array[n];
        array[n] = temp;
    }
}

 

60. Permutation Sequence

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

 
Brute-force solution, TLE:
public class Solution {
  int count = 0;

  public String getPermutation(int n, int k) {
    boolean[] numUsed = new boolean[n];
    LinkedList<Integer> current = new LinkedList<Integer>();
    List<Integer> result = new ArrayList<Integer>();

    if (getPermutation(numUsed, current, result, n, k)) {
      StringBuilder sb = new StringBuilder();
      for (Integer i : result) {
        sb.append(i);
      }
      return sb.toString();
    }
    return "";
  }

  private boolean getPermutation(boolean[] numUsed, Deque<Integer> current, List<Integer> result, int n, int k) {
    if (current.size() == numUsed.length) {
      ++count;
      if (count < k)
        return false;
      result.addAll(current);
      return true;
    }
    for (int i = 1; i <= n; ++i) {
      if (numUsed[i - 1])
        continue;

      current.addLast(i);
      numUsed[i - 1] = true;
      if (getPermutation(numUsed, current, result, n, k))
        return true;
      current.removeLast();
      numUsed[i - 1] = false;
    }
    return false;
  }
}

 

Do calculation to figure out which is the kth permutation:
public class Solution {
  public String getPermutation(int n, int k) {
    int[] factorial = new int[n + 1];
    //factorial = {1, 1, 2, 6, 24, ... n!}
    int sum = 1;
    factorial[0] = 1;
    for (int i = 1; i <= n; i++) {
      sum *= i;
      factorial[i] = sum;
    }
    List<Integer> numbersNotUsedYet = new ArrayList<>();
    //numbersNotUsedYet = {1, 2, 3, 4}
    for (int i = 1; i <= n; i++) {
      numbersNotUsedYet.add(i);
    }

    --k;
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= n; i++) {
      int index = k / factorial[n - i];
      sb.append(String.valueOf(numbersNotUsedYet.get(index)));
      numbersNotUsedYet.remove(index);
      k -= index * factorial[n - i];
    }
    return String.valueOf(sb);
  }
}

 

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
 
 
public class Solution {
  int N;
  int K;

  public List<List<Integer>> combine(int n, int k) {
    N = n;
    K = k;
    List<List<Integer>> results = new LinkedList<>();
    permute(results, 1, new ArrayDeque<>());
    return results;
  }

  private void permute(List<List<Integer>> results, int from, Deque<Integer> current) {
    if (current.size() == K) {
      List<Integer> currentCopy = new ArrayList<>(current);
      results.add(currentCopy);
      return;
    }

    for (int i = from; i <= N; ++i) {
      current.add(i);
      permute(results, i + 1, current);
      current.removeLast();
    }
  }
}

 

转载于:https://www.cnblogs.com/neweracoding/p/5477547.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值