基础算法

一、全排列

void prim(List<Character> list, List<Character> res, int r, int x) {
    if(res.size() == r) {
        System.out.println(res);
        return;
    }
    for(int i = x; i < list.size(); i++) {
        List<Character> t = new LinkedList<Character>(list);
        res.add(t.remove(i));
        // 当 x 位置用 0 代替时,组合可重复,否则反之
        prim(t, res, r, 0);
        res.remove(res.size() - 1);
    }
}

 

二、组合 

//从a中取k个 的 组合(标记法)
void dfs(int[] a, int[] take, boolean[] f, int num, int k, int x){
    if(num == k){
        for(int i = 0; i < k; i++)
            System.out.print((char)(take[i]+'A'));
        System.out.print("\n");
        return;
    }
    for(int i = x; i < a.length; i++){
        if(!f[i]){
            f[i] = true;
            take[num] = a[i];
            dfs(a, take, f, num+1, k, i);
            //当i位置用0代替时,组合可重复,否则反之
            f[i] = false;
        }
    }
}

 

三、快速排序

 

void Qsort(int list[], int left, int right) {
    if (left >= right)
        return;
    int t = list[left];
    int i = left, j = right;
    while (i != j) {
        while (i < j && list[j] >= t) j--;
        int temp = list[i];
        list[i] = list[j];
        list[j] = temp;

        while (i < j && list[i] <= t) i++;
        temp = list[i];
        list[i] = list[j];
        list[j] = temp;
    }
    Qsort(list, left, i);
    Qsort(list, i + 1, right);
}

 

 

四、最大公约数和最小公倍数  

 

int gcd(int a, int b) {
    int mod = a % b;
    while (mod != 0) {
        a = b;
        b = mod;
        mod = a % b;
    }
    return b;
}
// 公倍数 :a*b/gcd(a, b);

五、二分查找

int searchInsert(int[] nums, int target) {
    int left = 0;
    int right = nums.length;
    int mid = right / 2;
    while (left < right) {
        if (nums[mid] == target)
            return mid;
        if (nums[mid] < target)
            left = mid + 1;
        else
            right = mid;
        mid = right /2 + left / 2;
    }
    return left;
}

 

posted @ 2019-01-29 14:01  MoonTwilight  阅读(197)  评论(3编辑  收藏  举报