找到达到某个总和的最小迭代次数

时间:2015-10-29 06:46:27

标签: algorithm

我试图解决这个问题几个星期,但无法达成解决方案。 首先,两个数字X和Y都等于1.一次只有X+YY+X个有效选项。我们需要找到达到特定数字的最小迭代次数。

例如:如果数字是5

X=1, Y=1; X = X+Y

X=2, Y=1; Y = X+Y

X=2, Y=3; Y = Y+X

X=2, Y=5; Stop answer reached 

我的观点:如果一个数字是奇数,则说23,减1.现在值= 22.找到除以22 = 11的最大数字。现在通过加1来达到数字,以便:

X=11; Y=1 ; Y=Y+X

X=11; Y=12; X=X+Y

X=23, answer reached

但是这种方法的问题是我不能递归地达到一个特定的数字,因为即使我达到某一点,比如X =所需的值,Y值也会被错放,我不能重复它来达到另一个值

2 个答案:

答案 0 :(得分:6)

现在我可以提供O(nlogn)解决方案。

该方法似乎是greatest common divisor

使用f(x, y)表示此状态的最小迭代次数。如果f(x-y, y) x>yf(x,y-x) x<y(x, y)可以达到此状态。我们可以看到,达到州O(logn)的方式是唯一的,我们可以在min( f(n, i) | 1 <= i < n) gcd中计算它。

答案是O(nlogn),因此复杂性为def gcd (n, m): if m == 0: return n return gcd (m, n%m) def calculate (x, y): if y == 0: return -1 return calculate (y, x%y) + x/y def solve (n): x = 0 min = n for i in xrange (1, n): if gcd (n, i) == 1: ans = calculate (n, i) if ans < min: min = ans x = i print min if __name__ == '__main__': solve (5)

python代码:

override func viewWillAppear(animated: Bool) {
    let imageView = UIImageView(image: UIImage(named: "UINavigationBarBackIndicatorDefault"))
    imageView.tintColor = UIColor.redColor()
    let label = UILabel.init()
    label.textColor = UIColor.redColor()
    label.text = "Blog"
    label.sizeToFit()

    let space = 6 as CGFloat
    label.frame = CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+space, label.frame.origin.y, label.frame.size.width, label.frame.size.height)
    let view = UIView(frame: CGRectMake(0, 0, label.frame.size.width+imageView.frame.size.width+space, imageView.frame.size.height))

    view.bounds = CGRectMake(view.bounds.origin.x+8, view.bounds.origin.y-1, view.bounds.size.width, view.bounds.size.height)
    view.addSubview(imageView)
    view.addSubview(label)

    //instead of adding the button, in my opinion the better approach is to use a gesture recognizer.

    let tap = UITapGestureRecognizer(target: self, action: "handleBack:")
    view.addGestureRecognizer(tap)
    view.userInteractionEnabled = true

    UIView.animateWithDuration(0.33, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {

        label.alpha = 0
        let orig = label.frame
        label.frame = CGRectMake(label.frame.origin.x+25, label.frame.origin.y, label.frame.size.width, label.frame.size.height)
        label.alpha = 1
        label.frame = orig

        }, completion: nil)

    let backButton = UIBarButtonItem(customView: view)

}

func handleBack(sender: AnyObject) {
}

答案 1 :(得分:4)

如果数字不是那么大(比如1000以下),你可以使用breadth-first search

考虑有向图,其中每个顶点是一对数字(X,Y),并且从每个这样的顶点有两个边到顶点(X+Y,Y)(X,X+Y)。从(0,0)在该图表上运行BFS,直至到达您需要的任何位置。