Data structure & Algorithm
  • Initial page
  • 1212
  • 121231
  • 2.algorithm
    • 2.1.backtracking
      • 2.1.1.連續序列的排列組合(可能會重複)
      • 2.1.3.一串數列中任取n個數字, 總共有幾種組合
      • 2.1.2.一串數列中取n個數字, 共有幾種組合
    • 2.5.Quick sort
    • 2.6.2.6.廣度優先搜尋 (Breadth-first Search)
    • 2.2.Binary Search
    • 2.1.Backtracking
    • 2.4.河內塔 (Tower of Hanoi)
    • 2.7.動態規劃
    • 2.8.深度優先搜尋 (Depth-first Search)
    • 2.7.二分搜尋法
    • 2.3.分治法 (Divide and Conquer)
  • 2.Count and Say
  • 1.Leetcode Algorithm Practice
  • 2-count-and-say
    • c-solution
    • javascript-solution
  • Algorithm
  • 123
Powered by GitBook
On this page

Was this helpful?

  1. 2.algorithm
  2. 2.1.backtracking

2.1.1.連續序列的排列組合(可能會重複)

  • Example code:

         /**
         * Return an array of arrays of size *returnSize.
         * Note: The returned array must be malloced, assume caller calls free().
         */
        int fact(int n)
        {
            if (n==0) {
                return(1);
            }
            else {
                return(n*fact(n-1));
            }
        }
         void save(int* temp, int N, int ** res, int * index)
        {
            for (int i=0; i<N; ++i) {
                //printf("%d",temp[i]);
                res[*index][i] = temp[i];
            }
            *index = *index + 1;
        }
    
        void backtrack(int* nums, int* temp, int* used, int n, int N, int ** res, int * index)
        {
            if (n == N) {
                save(temp, N, res, index);
                return;
            }
    
            for (int i=0; i < N; i++){
                if (!used[i])
                {
                    used[i] = 1;
                    temp[n] = nums[i];
                    backtrack(nums, temp, used, n+1, N, res, index);
                    used[i] = 0;
                }
            }
        }
        void enumerate_permutations(int* nums, int* temp, int* used, int N, int ** res)
        {
            for (int i=0; i<N; i++) {
                used[i] = 0;
            }
            int index =0;
            backtrack(nums, temp, used, 0, N, res, &index);
        }
        int** permute(int* nums, int numsSize, int* returnSize) 
        {
            int length = fact(numsSize);
            int ** ary = (int **) malloc (length * sizeof(int *));
            for (int i=0; i< length; i++){
                ary[i] = (int *)malloc(numsSize * sizeof(int));
            }
            int* used = (int *)malloc(numsSize * sizeof(int));
            int* temp = (int *)malloc(numsSize * sizeof(int));
            *returnSize = length;
            enumerate_permutations(nums, temp, used, numsSize, ary);
    
            return ary;    
    
        }
Previous2.1.backtrackingNext2.1.3.一串數列中任取n個數字, 總共有幾種組合

Last updated 5 years ago

Was this helpful?