使用Digit DP和二进制搜索找到具有特定属性的第K个数字

时间:2017-09-01 03:48:48

标签: algorithm dynamic-programming

我最近遇到了一个问题,要求您找到满足某个属性的第K个数字。例如:

  

找到其总和等于60的第K个数字。

当我读到数字动态编程时,我了解到我们可以“使用二进制搜索和计数功能”来做到这一点。

我尝试了什么

我使用数字DP编写了一个计数函数F(N),给定数字N,计算[1, N]范围内所有数字,其总和等于60。现在,如果我有两个数字X和Y,那么X < Y,那么F(X) <= F(Y)。我用这个观察来编写一个二元搜索方法,它计算两个值,即下限和上限。

Lower Bound: the last number for which F(N) < K

Upper Bound: the last number for which F(N) <= K

然后我从Lower Bound迭代到Upper Bound找到答案。

我的问题

我想知道的是,这种方法是否正确?

  • 如果不是,我们该如何解决这个问题?
  • 如果是,有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

如果您只需要使用数字dp和二进制搜索,则答案的起点似乎是正确的。但我无法理解upperboundlowerbound的用途是什么,甚至是否需要。

以下是我在制作函数F() -

后如何处理这个问题
binary_search(int start,int end,int k){
    int mid=(start+end)/2;

    //mid is answer only if F(mid) has exactly k numbers and F(mid-1) has k-1 numbers
    if(F(mid)==k&&F(mid-1)==k-1) return mid;

    //if F(mid) has less than k numbers we need to check for greater numbers for answer
    else if(F(mid)<k) return binary_search(mid+1,end,k);

    //finally if F(mid) has more than or equal to k numbers we check smaller numbers for answer
    else return binary_search(start,mid-1,k);
}

(琐碎的建议)当你创建函数F(N)时,你应该这样计算并存储F(x) x属于范围[1,N]的值{/ 1}}。