算法刷题 DAY29

491.递增子序列

//不能进行排序,因为会改变原序列顺序→区别集合(无序)
//在所有树节点收获结果(同子集)
//子集问题(在所有结点收集结果)不用return(会在for循环判断条件自动返回)

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

int* path;
int path_index;
int** res;
int res_index;

int find(int* uset, int usetSize, int key) {
    int i;
    for(i = 0; i < usetSize; i++) {
        if(uset[i] == key)
            return 1;
    }
    return 0;
}

void backtracking(int* nums,int numsSize,int** returnColumnSizes,int start_index){
     
     int* uset = (int*)malloc(sizeof(int) * numsSize);
    int usetTop = 0;
    
    if(path_index>=2){
        int* temp=(int*)calloc(path_index,sizeof(int));
        memcpy(temp,path,sizeof(int)*path_index);
        (*returnColumnSizes)[res_index]=path_index;
        res[res_index++]=temp;
    }
    
    if(start_index>=numsSize) return;   
   // int* used=(int*)calloc(201,sizeof(int));

    for(int i=start_index;i0&&nums[i]

46.全排列

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

int* path;
int path_index;
int** res;
int res_index;
int* used;//设在全局位置用于树层去重

void backtracking(int* nums,int numsSize){

    if(path_index==numsSize){//收集结果
        int* temp=(int*)calloc(numsSize,sizeof(int));
        memcpy(temp,path,sizeof(int)*numsSize);
        res[res_index++]=temp;
        return;
    }

    for(int i=0;i

47.全排列 II

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

int* path;
int path_index;
int** res;
int res_index;
int* used;

int cmp(const void* str1,const void* str2){
    return *(int*)str1>*(int*)str2;
}

void backtracking(int* nums,int numsSize){

    if(path_index==numsSize){
        int* temp=(int*)calloc(numsSize,sizeof(int));
        memcpy(temp,path,sizeof(int)*numsSize);
        res[res_index++]=temp;
        return;
    }

    for(int i=0;i0&&nums[i]==nums[i-1]&&used[i-1]==0)) continue;
        used[i]=1;
        path[path_index++]=nums[i];
        backtracking(nums,numsSize);
        path_index--;
        used[i]=0;
    }

}

int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {

    (*returnSize)=0;
    if(numsSize==0) return NULL;
     
    qsort(nums,numsSize,sizeof(int),cmp);
    path=(int*)calloc(8,sizeof(int));
    path_index=0;
    res=(int**)calloc(50000,sizeof(int*));
    res_index=0;
    used=(int*)calloc(8,sizeof(int));

    backtracking(nums,numsSize);

    (*returnColumnSizes)=(int*)calloc(res_index,sizeof(int));
    for(int i=0;i

你可能感兴趣的:(算法,数据结构,leetcode,c语言,c++)