给定一个数组数字求其全排列(leetcode46):
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
思路:回溯法的练习题。因为我们找到的全排列的长度每个都还是等于数组长度。所以对于每个位置都重数组中找一个未被使用过的(用一个used数组记录是否被使用过),当找到位置等于数组长度了,就是找到了一个排列,即递归的出口。每次递归找下一个位置之后,回溯上一个位置,并将其used置为false。
public class L46Permutations {
public static void main(String[] args) {
int[] nums = {1,2,3};
System.out.println(permute(nums));
}
static List> res = new ArrayList>();
static boolean[] used ;
public static List> permute(int[] nums) {
used = new boolean[nums.length];
if(nums.length == 0){
return null;
}
helper(nums,0,new ArrayList());
return res;
}
private static void helper(int[] nums, int index, ArrayList list) {
if(index == nums.length){
System.out.println("index:"+index+" list:"+list);
res.add(new ArrayList(list));
System.out.println(res);
return ;
}
for(int i = 0 ; i < nums.length; i++){
if(!used[i]){
list.add(nums[i]);
used[i] = true;
helper(nums,index+1,list);
list.remove(list.size()-1);
used[i] = false;
}
}
}
}
求从1~n中选k个数的所有组合(leetcode77):
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
class Solution {
List> res = new ArrayList>();
public List> combine(int n, int k) {
helper(n,k,1,0,new ArrayList());
return res;
}
public void helper(int n, int k, int start,int index,ArrayList list){
if(index == k){
res.add(new ArrayList(list));
return;
}
for(int i = start; i <= n; i++){
list.add(i);
helper(n,k,i+1,index+1,list);
list.remove(list.size()-1);
}
}
}