1. 程式人生 > >給定一個數組數字求其的全排列 && 求1~n選k個數的所有組合

給定一個數組數字求其的全排列 && 求1~n選k個數的所有組合

給定一個數組數字求其全排列(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<List<Integer>>  res = new ArrayList<List<Integer>>();
	static boolean[]  used ;
	public static List<List<Integer>> permute(int[] nums) {
		used = new boolean[nums.length];
        if(nums.length == 0){
        	return null;
        }
        helper(nums,0,new ArrayList<Integer>());
        return res;
	}

	private static void helper(int[] nums, int index, ArrayList<Integer> list) {
		if(index == nums.length){
			System.out.println("index:"+index+"     list:"+list);
			
			res.add(new ArrayList<Integer>(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],
]
思路:與上題思路類似,不過每次選完當前的數,遞迴呼叫下一個位置就只能從當前數+1開始選了,因為是求組合,不能重複選擇。
class Solution {

    List<List<Integer>> res = new ArrayList<List<Integer>>();
	
    public List<List<Integer>> combine(int n, int k) {
    	helper(n,k,1,0,new ArrayList<Integer>());
    	return res;
    }
    
    public void helper(int n, int k, int start,int index,ArrayList<Integer> list){
    	if(index == k){
    		res.add(new ArrayList<Integer>(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);
    	}
    }
}